Wednesday, July 3, 2024
HomeLanguagesPythonid() function in Python

id() function in Python

In Python, the id() function is a built-in function that returns the unique identifier of an object. The identifier is an integer, which represents the memory address of the object. The id() function is commonly used to check if two variables or objects refer to the same memory location.

Syntax: id(object)

Return: a unique integer for a given object

Example:

Python3




x = 42
y = x
z = 42
 
print(id(x)) 
print(id(y))  # (same as x)
print(id(z))  # (same as x and y)


Output :

10731304
10731304
10731304

As we can see the function accepts a single parameter and is used to return the identity of an object. This identity has to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. If we relate this to C, then they are actually the memory address, here in Python it is the unique id. This function is generally used internally in Python. 

Python id() function Examples

Python id() for Inbuilt DataTypes

In this example, we are printing the id of multiple datatypes like strings and lists.

Python3




# This program shows various identities
str1 = "geek"
print(id(str1))
 
str2 = "geek"
print(id(str2))
 
# This will return True
print(id(str1) == id(str2))
 
# Use in Lists
list1 = ["aakash", "priya", "abdul"]
print(id(list1[0]))
print(id(list1[2]))
 
# This returns false
print(id(list1[0])==id(list1[2]))


Output :

140252505691448
140252505691448
True
140252505691840
140252505739928
False

Python id() for custom object

In this example, we are creating the Python class and we are creating two Python class objects and checking their ids.

Python3




class MyClass:
    pass
 
# Create two instances of MyClass
obj1 = MyClass()
obj2 = MyClass()
 
# Print the id of each object
print(id(obj1))
print(id(obj2))


Output :

139783388205328
139783388205392

Python id() with Sets

In this example, we are using the id function on sets in Python.

Python3




set1 = {1, 2, 3}
set2 = {3, 2, 1}
set3 = {1, 2, 3}
 
print(id(set1))  # Output: <id1>
print(id(set2))  # Output: <id2>
print(id(set3))  # Output: <id3>


Output :

139755710961408
139755710961184
139755709277664

Python id() with Tuples

In this example, we are using the id function on tuples in Python.

Python3




tuple1 = (1, 2, 3)
tuple2 = (3, 2, 1)
tuple3 = (1, 2, 3)
 
print(id(tuple1))  # Output: <id1>
print(id(tuple2))  # Output: <id2>
print(id(tuple3))  # Output: <id3>


Output :

140102982048128
140102982084288
140102982048128

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments