Sobes.tech
Middle+

How to get the address of an object in memory in Python? How does the 'is' operator understand that two objects refer to the same one?

sobes.tech AI

Answer from AI

In Python, you can get the memory address of an object using the built-in id() function. It returns a unique identifier for the object, which usually corresponds to its memory address (although this is not guaranteed by the specification, but in CPython it is exactly that).

Example:

obj = []
print(id(obj))  # Will output the memory address of the object

The is operator compares two objects by their identifiers, that is, by the result of id(). If id(a) == id(b), then a is b will return True, meaning both variables refer to the same object in memory.

Thus, is checks for object identity, not equality by value.