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 thisInstead of thisWhy?
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:

OperatorMeaningChecks...
==EqualityValues (__eq__)
isIdentityMemory reference

๐Ÿ” TL;DR:

โœ… Use is None and is not None โ€” it's the Pythonic and reliable way to test for None.