๐ Python: is vs. == โ Same Value, Different Object
Two lists contain exactly the same elements. You compare them, and Python says they’re equal.
Then you use is, and Python says they’re different.
Is Python contradicting itself? Nope. You’re asking two different questions.
The discovery: Equality isn’t identity
Take a look:
first = [1, 2, 3]
second = [1, 2, 3]
print(first == second) # True
print(first is second) # False
== asks whether the objects compare equal in value. For lists, that means they contain corresponding equal elements.
is asks whether both references point to the exact same object.
Although these lists contain identical values, Python created two distinct list objects.
Now compare this:
first = [1, 2, 3]
second = first
print(first == second) # True
print(first is second) # True
Here, both variables refer to the same list.
The distinction matters when you mutate objects. If second refers to first, changing the list through either variable affects the same underlying object.
See the official Python documentation on comparisons.
The exception you’ll use every day: None
For optional values, the idiomatic check is:
def greet(name=None):
if name is None:
return "Hello, stranger!"
return f"Hello, {name}!"
Why use is None instead of == None?
None is a singleton, so identity is the appropriate test. Python’s style guidance recommends using is or is not when comparing against singletons such as None.
It also avoids invoking a custom equality implementation that might give surprising results.
See PEP 8’s programming recommendations.
The important nuance: Don’t rely on object caching
You might encounter examples where two separately written integer or string expressions compare identical with is.
Don’t use that as a shortcut.
Python implementations may reuse certain objects, and compiler optimizations can affect observed identity. Such behavior isn’t a substitute for a value comparison.
For ordinary values, use ==. For identity checks, use is. And for None, use is None.
The takeaway โ
Remember the question each operator asks:
==: Do these objects compare equal?is: Are these references pointing to the same object?
Choose the question you actually mean to ask. Your future self will appreciate the distinction.