Python id() Function – Tutorial with Examples

The id() function in Python is a built-in function that returns a unique identifier for an object. The identifier is an integer that is guaranteed to be unique and constant for this object during its lifetime. The id() function is used to check the identity of an object, which is helpful when debugging or testing code.

Syntax

id(object)

Parameters

object – the object whose identity is to be returned

Return Value

The id() function returns an integer, which is a unique identifier for the object passed as an argument.

Examples

Example 1: Identity of an Integer Object

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

Output:

140714932765344
140714932765344

In this example, two integer objects x and y are created with the same value 123. The id() function is used to check the identity of these objects. The output shows that both x and y have the same identity, which means that they are the same object in memory.

Example 2: Identity of a String Object

x = "hello"
y = "hello"
print(id(x))
print(id(y))

Output:

2138337754848
2138337754848

In this example, two string objects x and y are created with the same value "hello". The id() function is used to check the identity of these objects. The output shows that both x and y have the same identity, which means that they are the same object in memory.

Example 3: Identity of a List Object

x = [1, 2, 3]
y = [1, 2, 3]
print(id(x))
print(id(y))

Output:

139930019981504
139930020088000

In this example, two list objects x and y are created with the same elements [1, 2, 3]. The id() function is used to check the identity of these objects. The output shows that both x and y have different identities, which means that they are not the same object in memory, even though they have the same elements.

Use Cases

The id() function can be used in the following scenarios:

  • To check the identity of an object, which can be helpful when debugging or testing code
  • To determine if two objects are the same object in memory or not
  • To identify an object in memory when working with complex data structures like lists or dictionaries

In conclusion, the id() function is a useful tool in Python when working with objects and their identities in memory. It provides a unique identifier for an object and helps in understanding the relationship between objects in memory.

Leave a Reply

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