Data Model
Equality and Identity
Equal containers can be different objects. == compares list contents, while is checks whether both names refer to the same list object.
Source
left = [1, 2, 3]
right = [1, 2, 3]
print(left == right)
print(left is right)Output
True
FalseIdentity matters when objects are mutable. same is another name for left, so mutating through one name changes the object seen through the other.
Source
same = left
same.append(4)
print(left)
print(same is left)Output
[1, 2, 3, 4]
TrueUse is for singleton identity checks such as None. This asks whether the value is the one special None object.
Source
value = None
print(value is None)Output
Trueis for integers is unreliable because CPython caches small integers (roughly -5 to 256) but not larger ones. Two equal large integers can be different objects. Use == for value comparisons; reserve is for singletons.
Source
small_a = 100
small_b = 100
print(small_a is small_b)
big_a = int("1000")
big_b = int("1000")
print(big_a is big_b)
print(big_a == big_b)Output
True
False
TrueNotes
- Use
==for ordinary value comparisons. - Use
isprimarily for identity checks against singletons such asNone. - Equal mutable containers can still be independent objects.
- Never use
isto compare numbers; CPython's small-integer cache makes the result an implementation detail.
See also
- prerequisite: None
- prerequisite: Values
- next depth: Object Lifecycle
- related: Mutability
Run the complete example
Expected output
True
False
[1, 2, 3, 4]
True
True
True
False
True
Execution time appears here after you run the example.