Python built-in Method - id()

www.‮i‬giftidea.com

The id() method in Python is a built-in function that returns the unique identifier of an object. The identifier is an integer that is guaranteed to be unique and constant for a given object during its lifetime.

The syntax for id() is as follows:

id(object)

Here, object is the object whose identifier is to be returned.

For example:

x = 10
y = "Hello, world!"
z = [1, 2, 3]

print(id(x))  # Output: 140701265524384
print(id(y))  # Output: 2894988548688
print(id(z))  # Output: 2894990505728

In the example above, we define three objects: an integer x, a string y, and a list z. We use the id() function to get the unique identifier of each object.

The id() function is useful when you need to check if two variables refer to the same object. If two variables have the same identifier, they refer to the same object. For example:

a = [1, 2, 3]
b = a
print(id(a) == id(b))  # Output: True

In the example above, we define a list a and assign it to a variable b. Since b is just another reference to the same object as a, the id() function returns True when we compare their identifiers.

The id() function is used internally by Python to implement many of its built-in data structures and algorithms. It can also be used in your own code to generate unique identifiers or to implement custom object equality tests.