is vs == in Python

In Python, the is operator and the == operator serve different purposes. Understanding the distinction between them is crucial for writing accurate and efficient code.


The is Operator

The is operator checks object identity, meaning it evaluates to True if two variables point to the same object in memory.

Example

x = [1, 2, 3]
y = x
z = [1, 2, 3]

print(x is y)  # True: x and y reference the same object.
print(x is z)  # False: x and z reference different objects.
Info

The is operator is often used to compare to singletons like None.

Example:

x = None
if x is None:
    print("x is None")

The == Operator

The == operator checks value equality, meaning it evaluates to True if the values of two objects are the same, regardless of whether they are the same object in memory.

Example

x = [1, 2, 3]
y = x
z = [1, 2, 3]

print(x == y)  # True: x and y have the same value.
print(x == z)  # True: x and z have the same value.
Pitfall

Two objects can have the same value (==) but not be the same object (is). This distinction is critical when comparing mutable objects like lists and dictionaries.


Key Differences Between is and ==

Featureis (Identity)== (Equality)
PurposeChecks if two objects are the same instance in memory.Checks if two objects have the same value.
ComparisonCompares memory addresses.Compares object values.
Common UsageUsed with singletons (e.g., None).Used for general equality checks.
Deep Dive

Example: Comparing Integers and Strings

For small integers and strings, Python may reuse the same memory location (due to interning), so is might return True. However, this behavior should not be relied upon for value comparison.

a = 256
b = 256
print(a is b)  # True (because of interning)

x = 1000
y = 1000
print(x is y)  # False (no interning for larger integers)

When to Use is vs ==

  • Use is when checking for identity (e.g., x is None).
  • Use == when checking for equality of values.
Task

Task: Practice Identity and Equality

  1. Identity Check: Create two variables pointing to the same list and verify their identity using is.

    Example:

    a = [1, 2, 3]
    b = a
    print(a is b)  # True
    
  2. Value Check: Create two variables with identical values but different objects and verify equality using ==.

    Example:

    a = [1, 2, 3]
    b = [1, 2, 3]
    print(a == b)  # True
    print(a is b)  # False
    
  3. Special Case with Integers: Explore the behavior of is with small and large integers.

    Example:

    x = 100
    y = 100
    print(x is y)  # True
    
    x = 1000
    y = 1000
    print(x is y)  # False
    

Copyright © 2025 Devship. All rights reserved.

Made by imParth