Python id() Method
The id()
function returns an identity of an object. In Python, all variables or literal values are objects, and each object has a unique identity as an integer number that remains constant for that object throughout its lifetime.
Syntax:
id(object)
Parameters:
object: The object whose identity needs to by returned.
Return Value:
Returns an integer value.
Id of Literal Values
All the literal values are objects in Python. So they will have Id values. The following example shows the identity of literal values.
print("Id of 10 is: ", id(10))
print("Id of 10.5 is: ", id(10.5))
print("Id of 'Hello World' is: ", id('Hello World'))
print("Id of list is: ", id([1, 2, 3, 4, 5]))
Id of 10 is: 8791113061
Id of 10.5 is: 3521776
Id of 'Hello World' is: 60430408
Id of list is: 5466244
Note that output will be different on your local PC.
Id of Variables
The id()
method also returns the identity of a variable or object, as shown below.
num = 10
mystr = 'Hello World'
print("Id of num is: ",id(i))
print("Id of mystr is: ",id(mystr))
Id of num is: 140730065134256
Id of mystr is: 1838584467312
The identity of the two same values is the same, as shown below.
num = 10
print("Id of num is: ", id(num))
print("Id of 10 is: ",id(10))
Id of i is: 8791113061696
Id of 10 is: 8791113061696
In the above example, the id of 10 and variable num
are the same because both have the same literal value.
Id of Custom Class Objects
The following gets an id of the user defined class's object.
class student:
name = 'John'
age = 18
std1 = student()
print(id(std1))
std2 = student()
print(id(std2))
std3 = student()
std3.name = 'Bill'
print(id(std2))
58959408
59632455
58994080
Above, each object has a different id irrespective of whether they have the same data or not.