is vs ==

Learn the difference between Python’s is and == operators. Understand identity vs equality with examples using integers, strings, lists, and None.

Loading...
is vs ==

In Python, is and == are both comparison operators that can be used to check if two values are equal.

Key Differences Between is and ==

Feature is ==
Purpose Checks identity (same memory location). Checks equality (same value).
Returns True if objects are the same instance. True if objects have the same value.
Use Case Verify if two references point to the same object. Compare data for equality.
Example with Lists a is b returns False for two separate but equal lists. a == b returns True for lists with the same contents.

Example 1: Immutable Objects

# Immutable integers
a = 1000
b = 1000
 
print(a == b)  # True (values are the same)
print(a is b)  # False (different memory locations for large integers)
 
# Small integers (Python caches -5 to 256)
x = 100
y = 100
 
print(x == y)  # True
print(x is y)  # True (both point to the same cached object)
 
# Strings
s1 = "hello"
s2 = "hello"
 
print(s1 == s2)  # True
print(s1 is s2)  # True (string interning reuses memory)

Example 2: Mutable Objects

# Mutable lists
a = [1, 2, 3]
b = [1, 2, 3]
 
print(a == b)  # True (values are the same)
print(a is b)  # False (different objects in memory)
 
# Same object reference
c = a
print(a is c)  # True (both refer to the same object)

Example 3: None Comparisons

The is operator is often used to compare with None because None is a singleton in Python.

a = None
print(a is None)  # True
print(a == None)  # True, but using `is` is preferred stylistically.

PEP 8 recommends using is for None checks, because it’s explicit and slightly faster.


When to Use is vs ==

  • Use is:
    • To check if two variables refer to the same object.
    • Comparing with None: if obj is None:
    • Verifying identity of singletons or cached objects.
  • Use ==:
    • To check if the values of two variables are equal.
    • Suitable for most comparisons involving data structures (lists, strings, dictionaries, etc.).

👉 Next tutorial: Python Object Oriented Programming

Support my work!