Home >Backend Development >Python Tutorial >Why do empty tuples, dictionaries, and lists share memory addresses in CPython, and why is this not related to mutability?
Why Do Empty Tuples, Dictionaries, and Lists Share Memory Addresses in CPython?
In CPython, empty containers (tuples, dictionaries, and lists) exhibit peculiar behavior regarding their object identifiers. Specifically, empty tuples, such as (), and empty dictionaries, such as {}, have the same memory address, and empty lists, such as [], also share a common address.
Explanation
When id({}) or id([]) is called in CPython, a temporary container is created and passed to the id function. However, before the function processes this temporary container, its memory address is recorded and passed on. The temporary container is then discarded, leaving only its memory address behind.
Subsequently, when another call to id({}) or id([]) is made before any other containers are created, the same memory address is likely to be assigned to the new temporary container. CPython's memory allocator often allocates memory blocks consecutively, making this scenario highly probable.
Since the 'id' function relies on memory addresses for object identification, it follows that id({}) == id({}) and id([]) == id([]) hold true. This behavior only occurs during the temporary existence of these empty containers and does not indicate that the containers share any inherent properties.
Distinction from Mutability
Mutability is not a direct factor in this phenomenon. However, it's crucial to note that mutable objects, such as lists, cannot be cached or re-used like immutable objects, such as tuples and strings. Consequently, id(x) != id(y) for any two distinct mutable objects, even if they contain identical elements.
Significance
An object's ID is only unique for its lifetime. After an object is destroyed or before it's created, another object can acquire the same ID.
The above is the detailed content of Why do empty tuples, dictionaries, and lists share memory addresses in CPython, and why is this not related to mutability?. For more information, please follow other related articles on the PHP Chinese website!