Skip to content
Tutorials Center
My learning

Topics

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.

Python
a = [1, 2]
b = a
print(id(a) == id(b))   # True

Try it

Python Same object or equal value?

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.

Python Identity is not stable knowledge

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

Python
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; is asks whether they are the same object. a is b is the same test as id(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), so is can be true for equal numbers. Do not rely on it; compare numbers and strings with ==.
  • Use is for singletons. x is None is the right way to test for None.
  • Mutable aliasing. Assigning a list to a second name copies the reference, not the list. Changes show through both names. Use list.copy() or copy.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.