SoFunction
Updated on 2025-03-02

Specific use of built-in Python function id

In Python programming,id()Functions are a very useful built-in function that can return a unique identifier of any object, i.e. the address of the object in memory. This function is very important when comparing objects, tracking object lifecycles, or performing memory management.

Functional Function

id()The main function of the function is to return the "id number" of the incoming object, that is, the memory address of the object. This address is an integer that can be used to determine whether the object is the same.

Function Syntax

id(object)
  • object: Must be a Python object.

Return value

The function returns an integer, which is the memory address of the object.

Sample code

Let's take a look at it with some simple examplesid()How functions work:

# Get the unique identifier of an integer objectnum = 42
print(id(num))  # The output may be: 140707460440496
# Get the unique identifier of the string objecttext = "Hello, world!"
print(id(text))  # The output may be: 2213742926448
# Get the unique identifier of the list objectmy_list = [1, 2, 3]
print(id(my_list))  # The output may be: 2213742979456
# The unique identifier of the object changes with the memory addressa = [1, 2, 3]
b = a
print(id(a))  # Output: 2213743232128print(id(b))  # Output: 2213743232128, same as a, because b is an alias for a

In the above example, we can seeid()How a function returns the memory address of an object of different types. When we create variablesbAsaWhen their alias areidare the same because they point to the same object in memory.

Things to note

  • For immutable objects (such as integers, strings, etc.), the same value usually shares the same memory address, while mutable objects (such as lists, dictionaries, etc.) usually have different memory addresses.
  • id()The memory address returned by the function is unique and constant over the life of the object, but may vary at different runtimes.

in conclusion

id()Functions are a simple and powerful tool in Python that provides a way to quickly get the memory address of an object. Whether it is debugging during development or when object comparison is required,id()All can come in handy.

This is the introduction to this article about the specific use of Python built-in function id(). For more related Python id() content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!