In Python, every object has a unique identifier, which can be obtained using the built-in id() function. This function returns an integer that represents the memory address of the object. In this article, we will explore the id() function in Python and demonstrate its usage with examples.
id()The syntax for id() is straightforward:
| id(object) |
where object is the object whose identifier we want to obtain.
id()Here are a few examples of how to use the id() function in Python:
|
# Integer
x = 42
print(id(x)) # Output: 140723234055184
# List
a = [1, 2, 3]
print(id(a)) # Output: 140723232912016
# String
s = "Hello, World!"
print(id(s)) # Output: 140723232174480
# Function
def foo():
print("Hello, World!")
print(id(foo)) # Output: 140723232909968
|
In the first example, we create an integer variable x and print its identifier using the id() function. The output is an integer, which represents the memory address of the x object.
In the second example, we create a list a and print its identifier using the id() function. Again, the output is an integer, which represents the memory address of the a object.
In the third example, we create a string s and print its identifier using the id() function. The output is, once again, an integer that represents the memory address of the s object.
Finally, in the fourth example, we define a simple function foo() and print its identifier using the id() function. As expected, the output is an integer that represents the memory address of the function object.
The id() function is a built-in function in Python that returns a unique identifier for any object. This identifier is an integer that represents the memory address of the object. By using the id() function in Python, you can easily obtain the memory address of any object, which can be useful in applications that require working with low-level data or memory management.