all Python 3Built-in functionsterm
id
introspection
Returns the unique identifier of an object for its lifetime; in CPython this is its memory address.
Syntax
id(object)
An id is unique only while the object is alive; once it is collected the same number can be handed to a new object, so storing an id and comparing it later is unreliable. Its one real use is asking whether two names point to the same object — which a is b expresses more readably — while == compares values. Watch out for interning as well: CPython caches small ints (-5 to 256) and short strings, so identical literals often share an id, and no logic should rest on that.
Examples
x = 42
y = x
print(id(x) == id(y)) # → True (одно и то же имя, один объект)
print(id(42) == id(42)) # → True (маленькие целые интернированы)
a = 'hello'; b = 'hello'
print(id(a) == id(b)) # → True (интернирование строк)
# Ловушка: id([]) == id([]) даёт True, и это НЕ значит «один объект».
# Первый список освобождается сразу после вычисления id, и второй получает
# тот же адрес. Сравнивать так нельзя — объекты должны быть ЖИВЫ:
first, second = [], []
print(id(first) == id(second)) # → False (два живых списка — разные объекты)
print(first is second) # → False (is сравнивает по id, но держит ссылки)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy