0
0
PythonHow-ToBeginner · 3 min read

How to Use id() Function in Python: Syntax and Examples

In Python, the id() function returns the unique identity (memory address) of an object as an integer. You use it by passing any object to id(object), and it gives a constant integer during the object's lifetime.
📐

Syntax

The id() function takes a single argument, which is the object you want to identify. It returns an integer that uniquely represents the object’s identity in memory during its lifetime.

  • id(object): Returns the unique id of the given object.
python
id(object)
💻

Example

This example shows how to use id() to get the unique identity of different objects like numbers and lists. It demonstrates that two variables pointing to the same object have the same id.

python
a = 10
b = a
c = [1, 2, 3]

print("id(a):", id(a))
print("id(b):", id(b))  # Same as id(a) because b points to the same object
print("id(c):", id(c))

# Changing c does not create a new object
c.append(4)
print("id(c) after append:", id(c))
Output
id(a): 9793376 id(b): 9793376 id(c): 140353204115456 id(c) after append: 140353204115456
⚠️

Common Pitfalls

One common mistake is expecting id() to give the same value for objects that look equal but are different objects. For example, two separate lists with the same content have different ids.

Also, id() values can be reused by Python after an object is deleted, so they are only unique during the object's lifetime.

python
list1 = [1, 2, 3]
list2 = [1, 2, 3]

print("id(list1):", id(list1))
print("id(list2):", id(list2))  # Different from list1 even if contents are same

# After deleting list1, its id may be reused
del list1
new_obj = []
print("id(new_obj):", id(new_obj))
Output
id(list1): 140353204115712 id(list2): 140353204115968 id(new_obj): 140353204115712
📊

Quick Reference

Remember these points when using id():

  • Returns an integer unique to the object during its lifetime.
  • Useful for checking if two variables point to the same object.
  • Not reliable for comparing object equality (use == for that).
  • Ids can be reused after an object is deleted.

Key Takeaways

Use id(object) to get the unique identity of an object in Python.
Objects with the same id are the exact same object in memory.
Two objects with equal content can have different ids.
Id values are unique only during the object's lifetime and can be reused.
Use id() to check object identity, not equality.