- Published on
12. Difference between == and "is" operators in Python
- Authors
12. Is None or == None, what should you use, and why? Is there a difference between == and is operators?
Yes, there is a difference between is
and ==
, and when dealing with None
, it's important to choose the right one.
โ Short Answer:
Always use is None
or is not None
, not == None
.
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # False (different objects)
print(a == b) # True (equal values)
๐ง Detailed Explanation:
is
checks identity
๐น - It checks whether two variables refer to the same object in memory.
None
is a singleton in Python โ there's only one instance of it.
x = None
if x is None:
print("x is None") # โ
preferred
==
checks equality
๐น - It checks whether two values are equal (using the
__eq__()
method). - It can be overridden in custom classes.
class Weird:
def __eq__(self, other):
return True
w = Weird()
print(w == None) # True (misleading!)
print(w is None) # False (correct!)
This is why == None
can lead to unexpected behavior, especially when working with objects that redefine equality.
โ Best Practice:
Use this | Instead of this | Why? |
---|---|---|
if x is None: | if x == None: | Safer, faster, and avoids override issues |
if x is not None: | if x != None: | Same reasons |
๐งช Quick Comparison:
Operator | Meaning | Checks... |
---|---|---|
== | Equality | Values (__eq__ ) |
is | Identity | Memory reference |
๐ TL;DR:
โ Use
is None
andis not None
โ it's the Pythonic and reliable way to test forNone
.