id()

Return an integer that is guaranteed to be unique and constant for an object for its lifetime — what the is operator compares.

                id(object)
              

Purpose

id(object) returns an integer that uniquely identifies an object for as long as it exists. Two names refer to the same object exactly when id(a) == id(b) — which is precisely what the is operator checks, so a is b and id(a) == id(b) always agree.

Example

a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)  # True  — equal contents
print(a is b)  # False — two distinct list objects
print(a is c)  # True  — c is another name for the same object

Behavior notes

  • Guaranteed by the language: the id is unique among currently-alive objects, and stays constant for that object’s whole lifetime.
  • Not guaranteed by the language: what the id actually is. In CPython, it happens to be the object’s memory address — that specific detail is a CPython implementation choice, not something the language specification requires, and other implementations are free to number objects differently.
  • Once an object is garbage collected, its id may be reused by a completely unrelated later object. An id is only meaningful for comparing objects you know are still alive at the same time.

Common mistakes

  • Comparing two ids captured at different points in a program and assuming they identify the original objects, without confirming both objects are still alive — a stale id can coincide with an unrelated object’s current id.
  • Using is to compare values instead of identity (e.g. if count is 0:) — is checks identity, not equality, and relying on it for value comparisons happens to work sometimes only because of CPython-specific small-integer caching, which is exactly the kind of implementation detail this site labels explicitly rather than lets you rely on by accident.

Implementation notes

The guarantee (unique, constant for the object’s lifetime) is a language-level promise. The value id() returns being a memory address is a CPython detail — this entry is labeled python + cpython for exactly that split.

Taught in these lessons

Related reference