Python id: How to Use id() Function In Python Example

Python id() is an inbuilt function that is used to get the identity of an object. Two objects with the non-overlapping lifetimes may have the same id() value. In CPython implementation, it is an address of the object in memory.

Python id() Example

Python cache is the id() value of commonly used the data types, such as the stringintegertuples, etc.  So you might find that multiple variables refer to the same object and have the same id() value if their values are the same.

Syntax

id(object)

The id() function takes the single parameter object.

# app.py

# integers
a = 11
b = 21
c = 19
d = 18

print(id(a))
print(id(b))
print(id(c))
print(id(d))

See the following output.

➜  pyt python3 app.py
4304849600
4304849920
4304849856
4304849824
➜  pyt

The id() function returns the identity of the object. This is an integer that is unique for the given object and remains constant during its lifetime.

Let’s see if we get similar behavior with string and tuples too.

# app.py

# tuples
t = ('Eleven', 'Mike')
print(id(t))

t1 = ('Dustin', 'Suzie')
print(id(t1))

# strings
s1 = 'Jane'
s2 = 'Jane'
print(id(s1))
print(id(s2))

See the following output.

➜  pyt python3 app.py
4358154504
4358154440
4356016256
4356016256
➜  pyt

As we can see, a function accepts the single parameter and is used to return the identity of the object. The identity has to be unique and constant for this object during the lifetime. 

Two objects with an non-overlapping lifetimes may have the same id() value.

Python cache the strings and tuple objects and use them to save the memory space.

We know that the dictionary is not immutable, So, if the id() function is different for different dictionaries even if the elements are the same.

# app.py

a1 = {"age": 26, "year": 1993}
a2 = {"age": 26, "year": 1993}
print(id(a1))
print(id(a2))

See the following output.

➜  pyt python3 app.py
4345653144
4345653216
➜  pyt

The dict objects are returning different id() value, and there seems no caching here.

#Python id() for custom object

See the following example.

# app.py

class Student:
    data = 0


e1 = Student()
e2 = Student()

print(id(e1))
print(id(e2))

See the following output.

➜  pyt python3 app.py
4349781216
4349781328
➜  pyt

Python id() value is the guaranteed to be unique and constant for the object. We can use this to make sure that two objects are referring to the same object in memory or not.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.