id() Function in Python

Python id() Function

The id() function in Python returns the unique identifier (integer) for an object. This identifier is unique and constant for the object during its lifetime. It is implemented as the object's memory address.

The syntax for the id() function is as follows:

id(object)

Here, object is the object for which you want to retrieve the identifier.

Let's look at some examples to understand how the id() function works:

x = 10
y = 10

print(id(x))  # Output: 140710327313296
print(id(y))  # Output: 140710327313296

In this example, both x and y are assigned the same value of 10. When we print the identifiers using the id() function, we get the same result for both x and y. This is because integers in the range [-5, 256] are cached and reused, so x and y refer to the same object.

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

print(id(list1))  # Output: 140710327013184
print(id(list2))  # Output: 140710327018304

In this example, we have two different list objects with the same contents. When we print the identifiers, we get different results because each list object has its own unique identifier.

Note that the id() function should not be used to compare objects for equality. It only provides a unique identifier for an object based on its memory address. To compare objects for equality, you should use the == operator or appropriate comparison methods.

Also, it's worth mentioning that the id() function is implementation-specific and may behave differently in different Python interpreters or versions.