Python: Difference between `is` and `==` (Identity vs Equality)

Published:
Last updated:
ByJeferson Peter
2 min read
Python
Share this post:

When learning Python, many developers wonder: what’s the difference between is and ==? At first glance, both seem to do the same thing — but they don’t. While == checks if two values are equal, is checks if two variables point to the same object in memory. Let’s explore this difference with practical examples.


Difference between is and == in Python

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)  # values equal?
print(a is b)  # same object?

# True
# False

a == b → returns True because both lists have the same values. ✘ a is b → returns False because they are two different objects, even if their contents are identical.


When two variables point to the same object

a = [1, 2]
b = a  # b points to the same list as a
print(a is b)

# True

Here, b is just another reference to the same object in memory. That’s why a is b returns True.


Gotcha: small integers and strings may be cached

Python sometimes reuses objects (called interning). That means two variables may actually point to the same object even if they look like separate values.

x = 256
y = 256
print(x is y)  # often True

x = 257
y = 257
print(x is y)  # may be False

Integers between -5 and 256 are usually cached, so is may return True unexpectedly.

The same can happen with strings:

s1 = "hello"
s2 = "hello"
print(s1 is s2)  # often True due to interning

That’s why relying on is for value comparison is risky.


Best practice: when to use is vs ==

  • ✅ Use == when comparing values:

    if user_input == "yes":
        print("Confirmed!")
    
  • ✅ Use is when checking identity, especially with None:

    if result is None:
        print("No value returned")
    
  • ❌ Don’t rely on is for integers or strings — caching may trick you.


Conclusion

In short:

  • == → compares values.
  • is → compares identity (same object in memory).

In practice, you’ll use == most of the time. Keep is for specific cases like checking if something is None. This makes your code more readable, predictable, and professional.

Share this post:
Python: Difference between `is` and `==` (Identity vs Equality) | CodeCraftPython