Why can equal Python lists be different objects?
Python 3.10+; standard library only. GIL discussion refers to conventional CPython builds, not optional free-threaded builds.
Detailed answer
== compares values through equality methods; is compares identity. Two separately created lists can contain the same values without sharing storage.
Assignment binds another name to the same object; it does not clone it. Mutating an aliased list is visible through every name referring to it.
Use is for singletons such as None and use == for normal value comparisons. Interpreter caching of small integers or strings is an implementation detail, not a comparison strategy.
Internal working
Names hold references to objects. The equality protocol can be customized with __eq__; identity cannot be changed by an ordinary equality override.
Practical scenario
Two request handlers share a list accidentally through a module-level default; an append in one handler appears in the other.
a = [1, 2]
b = a
c = [1, 2]
print(a is b, a is c, a == c) # True False TrueCommon mistakes
- Using is to compare strings.
- Assuming assignment copies containers.
Key takeaways
- Names bind to objects.
- Equality differs from identity.
- Use is None.
Follow-up challenges
- What does shallow copying preserve?
- Can __eq__ return NotImplemented?