Distinguish Object Identity, Type and Value
Core idea
An object has an identity, a type and a value. is tests whether two references designate the same object; == asks for equality, whose meaning can be customized by the type. type(x) gives the type; id(x) is an integer unique among simultaneously living objects. Aliasing shares an object, while constructing a new list creates a distinct one. Rebinding a name is not mutation.
Equal contents do not imply shared identity.
Observe shared mutation
Both names designate the same changed list.
Rebind without mutating
The new binding leaves the original list intact.
Common mistake
Never infer value equality using is on numbers or strings; reuse of immutable objects may differ by implementation. IDs can be reused after an object dies. CPython uses an address for id, but portable code must not rely on that.
Practice
Create two equal dictionaries and an alias of one. Predict identity and equality before and after modifying the alias.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Identity, type and value
Check your understanding of identity type and value.
What is printed?
a = [8]b = [8]print(a is b, a == b)What is printed?
a = {}b = aprint(id(a) == id(b))What is printed?
x = [1, 2]print(type(x).__name__)Which identity claim is portable?