Python id()

The id() method returns a unique integer (identity) of a passed argument object.

Example

a = 5
b = 6
sum = a + b

# id of sum variable
print("The id of sum is", id(sum))

# Output: The id of sum is 9789312

id() Syntax

The syntax of the id() method is:

id(object)

id() Parameter

The id() method takes a single parameter:

  • object - can be a class, variable, list, tuple, set, etc.

id() Return Value

The id() method returns:

  • the identity of the object (which is a unique integer for a given object)

Example 1: Python id()

# id of 5
print("id of 5 =", id(5))

a = 5

# id of a
print("id of a =", id(a))

b = a

# id of b
print("id of b =", id(b))

c = 5.0

# id of c
print("id of c =", id(c))

Output

id of 5 = 140472391630016
id of a = 140472391630016
id of b = 140472391630016
id of c = 140472372786520

Here, the id() method returns a unique integer number for every unique value it is used with.

In the above example, we have used the id() method with variables a, b and c and got their corresponding ids.

As you can see, the id() method returns the integer 140472391630016 for both a = 5 and 5.

Since both values are the same, the id is also the same.

Note: Since ID is an assigned memory address, it can be different in different systems. So, the output on your system can be different.


Example 2: id() with Classes and Objects

class Food:
    banana = 15

dummyFood = Food()
# id of the object dummyFood print("id of dummyFoo =", id(dummyFood))

Output

id of dummyFoo = 139980765729984

Here, we have used the id() method with the objects of classes.

When we use the id() method with the dummyFood object, we get the result 139984002204864.


Example 3: id() with Sets

fruits = {"apple", "banana", "cherry", "date"}
# id() of the set fruits print("The id of the fruits set is", id(fruits))

Output:

The id of the fruits set is 140533973276928

In the above example, we have used the id() method with a set fruit. In this case, we get the unique number as the id for the set - 140533973276928.


Example 4: id() with Tuples

vegetables = ("asparagus", "basil", "cabbage")

# id() with vegetable print("The id of the vegetables set is", id(vegetables))

Output:

The id of the vegetables set is 139751433263360

Here, we have used the id() method with a tuple.

The id() method returns a unique number 139751433263360 as the id of the tuple vegetable.


Recommended Readings:

Did you find this article helpful?