Site icon TestingDocs.com

Python id() Function

Overview

The Python id() function is used to get the unique identity of an object. This identity is an integer that is guaranteed to be unique and constant for the object during its lifetime. In other words, the id() function returns the object’s memory address.

The id is assigned to the object when it is created. This identity is unique and constant for this object during its lifetime.

Python id() Function

This function takes a single argument and returns the object’s unique identifier in Python.

Syntax

The general syntax of the id() function is as follows:

id(object)

The parameter object can be any object—for example, float, str, list, dict, tuple, class, etc.

Example

Let’s understand the concept with the help of an example Python program:

# Python program id() Function
# Python Tutorials – www.TestingDocs.com

# Define two variables
x = 79
y = 97

# Get the unique identity of the objects
identityX = id(x)
identityY = id(y)
print(“~~~~~~~~~~~Python id() Function~~~~~~~~~~”)
print(f”The memory address of x is: {identityX}”)
print(f”The memory address of y is: {identityY}”)
print(“—————————————–“)

x = y

# x refers the same object as y
identityX = id(x)
identityY = id(y)

print(f”The memory address of x is: {identityX}”)
print(f”The memory address of y is: {identityY}”)

 

Output

~~~~~~~~~~~Python id() Function~~~~~~~~~~
The memory address of x is: 140731916632952
The memory address of y is: 140731916633528
—————————————–
The memory address of x is: 140731916633528
The memory address of y is: 140731916633528

 

 

The variables x and y references two distinct objects. As a result, the id() function returns two unique identifiers.

In the next section of the program, we assign the object y to x. Now x and y reference the same object. We can notice in the program output that the next id() function calls return the same memory address.

Python Tutorials

Python Tutorial on this website can be found at:

https://www.testingdocs.com/python-tutorials/

More information on Python is available at the official website:

https://www.python.org

Exit mobile version