Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

id() Function in Python

Last Updated on October 18, 2023 by Ankit Kochar

The id function in Python plays a unique and powerful role as it allows you to obtain the identity of an object. Every object in Python has a unique identity, a number that distinguishes it from all other objects during its lifetime. This identity is assigned when an object is created and remains constant throughout its existence.
The id function in Python provides a way to access this identity, allowing you to verify whether two variables reference the same object and to gain insights into object behavior and memory management. Understanding how to use the id() function effectively is essential for Python developers, as it helps in debugging, memory optimization, and object comparison. In this article, we will delve into the intricacies of the id function in Python. We will explore its purpose, practical applications, and limitations. Additionally, we’ll discuss how this function relates to object-oriented programming, memory management, and best practices for using it in your Python code.

What is id() Function in Python?

id() is a built-in Python method that returns a unique id for the given object, and this id must be unique throughout the object’s lifespan.
In Python, each object and variable has a unique id. Consider this to be similar to the process Ids used by operating systems to uniquely identify each process. When a Python object is saved in memory, it is assigned a unique identification number, which helps the Python interpreter run better and use memory more efficiently. The id() function returns the object’s unique identification. The id() function in Python does not require any further installation; it comes standard with any Python installation (e.g., Anaconda, Python IDLE, etc.).

This method can be called without using any additional import statements. When an object is created in memory, it is allocated an ID. The ID is the memory address of the object, and it will be different each time you execute the program. except for some objects, such as integers from -5 to 256, which have a constant unique id.

Syntax of id() Function in Python

The syntax of the id function in Python is:

id(object)

where,

object = int, float, string, tuple, list, class, function, etc.

Let’s have a look at how id function in python works:

prepBuddy = 25
print(prepBuddy)
print(id(prepBuddy))

Output:

25
22761063107632

Here, a variable prepBuddy was created and the value 25 was stored. The value returned by id() for the variable prepBuddy is its unique id. Only the variable prepBuddy can hold that id.

Parameters of id() Function in Python

The object parameter is the only parameter passed to the id() function. The object parameter can be anything from constants and variables to a Python-created custom class object.

Return Value of id() Function in Python

The id() function returns a unique id that is held only by the specified object. id() function will always return an integer number as the unique id.

prepBuddy = 12
print(prepBuddy)
print(id(prepBuddy))
print("Return type of id() : ", type(id(prepBuddy)))

Output:

12
22865930246800
Return type of id() : 

Examples of id() Function in Python

Let’s look at some examples of how to use the id function in Python:

Example 1
Here’s an example where the id() function returns identical values for two objects in Python:

x = 'PrepBytes'
y = 'PrepBytes'

print(id(x)) 
print(id(y))  

print(id(x) == id(y))

Output:

22457225599472
22457225599472
True

Explanation – In this example, we create two string objects x and y, both of which have the same value of ‘PrepBytes’. Since strings are immutable in Python, the value of the object cannot be changed, and Python optimizes memory usage by sharing the same object in memory when two variables contain the same value. As a result, the id() function returns the same memory address for both x and y, and the equality comparison returns True.

Example 2
Here’s an example of using the id() function on immutable objects in Python

my_list1 = [12, 24, 31, 49]
my_list2 = [12, 24, 31, 49]

my_dict1 = {1: 'Hi', 2: 'PrepBytes'}
my_dict2 = {1: 'Hi', 2: 'PrepBytes'}

print(id(my_list1)==id(my_list2))
print(id(my_dict1)==id(my_dict2))

Output:

False
False

Example 3
Here’s an example of using the id() function on custom objects in Python:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person1 = Person("Manoj", 21)
person2 = Person("Ankit", 25)

print(id(person1)) 
print(id(person2))

Output:

23142764242208
23142764244416

Explanation – In this example, we define a Person class that has two attributes: name and age. We then create two instances of the Person class: person1 and person2. When we pass these objects to the id() function, it returns the memory address of the object referred to by each variable.

Since person1 and person2 are distinct objects in memory, they have different memory addresses, and the id() function returns a different integer for each object.

Conclusion
The id function in Python is a versatile tool that provides insight into the identity of objects. It serves various purposes, from object comparison to debugging and memory management. By leveraging the id function in Python, Python developers can gain a deeper understanding of how objects are stored and managed in memory.

In this article, we’ve explored the significance of the id function in Python and its practical applications. We’ve seen how it can be used to determine if two variables reference the same object and how it can help in debugging by revealing object identities. Additionally, we’ve discussed the limitations of the id() function, such as the fact that the identity value is not guaranteed to be unique across different runs of a Python program.

FAQs Related to id() Function

Here are some frequently asked questions about the id function in Python:

1. What is the purpose of the id() function in Python?
The id() function is used to obtain the identity of an object, which is a unique number assigned to that object. It is mainly used to determine if two variables reference the same object.

2. How can I use the id() function for debugging purposes?
You can use the id() function to compare the identities of objects and check if two variables point to the same object. This can be helpful when debugging code to identify object reference issues.

3. Is the identity value returned by id() guaranteed to be unique across different Python runs or sessions?
No, the identity value returned by id() is not guaranteed to be unique across different runs or sessions of a Python program. It is unique only within the current session.

4. Can the id() function be used to compare the contents of two objects, such as lists or dictionaries?
No, the id() function should not be used to compare the contents of objects. It only compares the identities of objects, not their values. For content comparison, you should use other methods or operators like ==.

5. Are there any performance considerations when using the id() function frequently in code?
Calling the id() function is relatively fast and efficient. However, excessive use of id() in performance-critical code may have a small impact, so it should be used judiciously in such cases.

Leave a Reply

Your email address will not be published. Required fields are marked *