Summary: In this tutorial, you will learn what is id() function in Python and when you should use it in your Python program.
id() in Python
In Python, the id()
is a built-in function that returns the unique identity of an object in the form of an integer. This identity is unique and constant for the object during its lifetime.
For example:
x = 5
print(id(x)) #10914496
Here the id()
function returned unique identity (in the form of an integer) of the object x
.
The id()
function can be used on any object (custom objects as well as built-in objects), including strings, numbers, lists, etc.
For example, you can define a custom class and use the id()
function on an instance of that class:
class MyClass:
def __init__(self, value):
self.value = value
obj = MyClass(5)
print(id(obj)) # Prints the unique identity of the obj object
When is id() function useful?
The id()
function is useful in several situations, including:
- Comparing object identities: The
id()
function can be used to determine if two variables refer to the same object or not. This is useful in cases where you want to compare the identity of two objects, rather than their values. - Debugging: When debugging code, the
id()
function can be used to check if multiple variables are referring to the same object or not. This can help identify unexpected behavior or bugs in your code. - Memory management: The
id()
function can be used to monitor the number of unique objects in memory. This can help identify memory leaks or other issues related to memory management. - Caching: The
id()
function can be used as a key in caching mechanisms, because the id of an object is guaranteed to be unique and constant during the lifetime of the object. - Object tracking: The
id()
function can be used in various tracking mechanisms, for example, tracking the objects that are currently in use, tracking the objects that have been created, etc.
Example 1: compare object identities
If two different variables refer to the same object, then, the id()
function will return the same identity for both variables.
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(id(x) == id(y)) # False
print(id(x) == id(z)) # True
In this example, x
and y
are two separate lists with the same values, so their identities are different. On the other hand, z
is assigned the value of x
, so they refer to the same object and have the same identity.
Example 2: Using the id()
function for caching
class MyClass:
def __init__(self, value):
self.value = value
cache = {}
def get_object(value):
if value in cache:
return cache[value]
obj = MyClass(value)
cache[value] = obj
return obj
obj1 = get_object(5)
obj2 = get_object(5)
print(id(obj1) == id(obj2)) # True
Here, we use a dictionary cache
to store the objects that have been created with a specific value.
When the get_object()
function is called with the same value multiple times, it returns the same object each time, because it uses the object’s identity as the key in the cache.