Python id() function
The id() function in Python returns a unique id for any specified object. For example:
a = [12, 42, 5, 5] b = (1, 43, 5) c = "Python Programming" print(id(a)) print(id(b)) print(id(c))
The snapshot given below shows the sample output produced by the above Python program, demonstrating the id() function:
Note: Every object in Python gets assigned its own unique id when it is created. Therefore, you'll get a different ID for the same object each time you run the program.
Python id() function syntax
The syntax of the id() function in Python is:
where obj refers to an object such as a list, string, tuple, class, etc.
Python id() function example
Here is an example of the id() function in Python.
num = 100 a = 100 print(id(100)) print(id(num)) print(id(a))
All three print() statements print the same output, which looks like this:
2245638378960 2245638378960 2245638378960
This is because the id of a particular one remains constant during the lifetime of a program.
Advantages of the id() function in Python
- Python's id() function generates a unique identifier for each object, making it useful for object identification and comparison.
- It can be used to determine if two variables refer to the same object, which can be crucial in certain programming scenarios.
- By comparing an object's current identifier with its previous identifier, the id() function can determine whether an object has been modified or reassigned.
Disadvantages of the id() function in Python
- The id() function returns an integer that is meaningless to the user and may be difficult to interpret without additional context.
- The unique identifier returned by id() is implementation-dependent and may differ between Python versions or Python interpreter implementations.
- Because it must generate a unique identifier for each object, the id() function may be computationally expensive for large or complex objects.
« Previous Function Next Function »
Liked this post? Share it!