Python Tutorials | Python's type() and id() Functions Explained

When working with Python, understanding the type and identity of your variables can help you debug, validate, and analyze your code. Python provides two built-in functions for this: type() and id().

This article breaks down these two functions with clear, real-world examples to help you grasp their usage effectively.

What is type()?

The type() function returns the data type of the object passed to it. It’s commonly used to check or validate variable types.

What is id()?

The id() function returns a unique identifier for an object. This ID represents the memory address where the object is stored (though not always directly visible as memory).

Example 1: Checking Type of an Integer

x = 10
print(type(x))

Returns: <class 'int'>

Example 2: Type of a String

name = "Alice"
print(type(name))

The type() function helps confirm the variable is a string.

Example 3: Type of a Float

price = 99.99
print(type(price))

This returns: <class 'float'>.

Example 4: Type of a Boolean

is_active = True
print(type(is_active))

Useful when validating user flags or toggle states.

Example 5: Type of a List

items = [1, 2, 3]
print(type(items))

Returns <class 'list'>. Helpful in data structure validation.

Example 6: Using id() to Check Object Identity

a = 5
b = 5
print(id(a))
print(id(b))

In Python, small integers are cached, so a and b might have the same ID.

Example 7: id() with Different Objects

x = "hello"
y = "world"
print(id(x))
print(id(y))

Each string has a different memory reference unless they are exactly the same and interned.

Example 8: id() with Mutables

numbers = [1, 2, 3]
print(id(numbers))
numbers.append(4)
print(id(numbers))

The ID remains the same because lists are mutable — their content can change without changing their identity.

Example 9: id() Changes for New Object

a = [1, 2, 3]
a = a + [4]
print(id(a))

In this case, a new object is created, so the ID changes. This demonstrates how reassignment differs from in-place changes.

Example 10: Comparing Objects Using id()

x = [1, 2]
y = x
print(id(x) == id(y))

Here, y points to the same object as x, so both IDs are equal. This is important when understanding references and memory.


Summary

  • type() tells you the class/type of any object.
  • id() gives the identity of the object in memory.
  • Two variables with the same value may or may not share the same ID depending on immutability and caching.
  • Use type() to validate inputs and id() to track memory references, especially with mutable types.

These two simple functions are essential tools for debugging and building a better understanding of how Python handles variables and memory.