Python Reference ยท Built-in Functions
Python id() function
Reference for Python id(): the identity of an object, how it relates to the is operator, aliasing, small-integer caching and why you should not rely on values.
The id() function returns an integer that identifies an object. During the object's lifetime no other object has the same identity. Two names that refer to the same object give the same id(), and that is exactly what the is operator tests.
You rarely need the number itself. id() is mostly a teaching and debugging tool, for answering "are these two names the same object or just equal values?". In CPython the number happens to be the object's memory address, but that is an implementation detail.
a = [1, 2] b = a print(id(a) == id(b)) # True
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
id(object)
| Name | Description |
|---|---|
object |
Any object. |
Return value: an int, unique among objects alive at the same time.
Usage notes
- Identity vs equality.
==asks whether two objects have equal values;isasks whether they are the same object.a is bis the same test asid(a) == id(b), but faster and clearer. - Never print or store ids as stable data. Values differ between runs and machines. An id can even be reused after the object is deleted, so an old number may point to a new object.
- Small-value caching. CPython reuses some immutable objects (small integers,
None,True, many short strings), soiscan be true for equal numbers. Do not rely on it; compare numbers and strings with==. - Use
isfor singletons.x is Noneis the right way to test forNone. - Mutable aliasing. Assigning a list to a second name copies the reference, not the list. Changes show through both names. Use
list.copy()orcopy.deepcopy()for independent copies. - Function arguments are passed as references to objects, so
id(param)inside a function equals the id of the argument you passed. - Not a memory address on other implementations. PyPy and others use different schemes.