Returns a unique id of an object
id() function returns a unique id for the specified object.
|object||Required||Any object (such as number, string, list, class etc.)|
What is ID of an Object?
In Python, every object has its own unique id.
Every time you create an object, a unique id is assigned to it.
The id is nothing but the address of the object in memory. So, it will be different for each time you run the program. But, there are some exceptions.
id() function to get a unique id of the object.
# string x = id('Hello!') print(x) # 34936992
# number x = id(9999) print(x) # 33739544
# list L = ['red', 'green', 'blue'] x = id(L) print(x) # 33866256
# custom object class myfunc: pass o = myfunc() print(id(o)) # 33666912
Compare Two IDs
To check if two objects have same id, use
Example: Check if ‘x’ and ‘y’ have the same id (point to the same object)
x = 42 y = x print(x is y) # True
is keyword is used for identity (id) comparison, while
== operator is used for equality (value) comparison.
In Python, every object has its own unique id. However, for the sake of optimization there are some exceptions.
Some objects have same id (actually one object with multiple pointer), like
- Small integers between
- Small interned strings (usually less than 20 character)
You can check this fact like following:
>>> 30 is 20+10 True >>> 300 is 200+100 False >>> 'aa'*2 is 'a'*4 True >>> 'aa'*20 is 'a'*40 False