is
vs ==
in PythonIn Python, the is
operator and the ==
operator serve different purposes. Understanding the distinction between them is crucial for writing accurate and efficient code.
is
OperatorThe is
operator checks object identity, meaning it evaluates to True
if two variables point to the same object in memory.
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.
The is
operator is often used to compare to singletons like None
.
Example:
x = None
if x is None:
print("x is None")
==
OperatorThe ==
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.
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.
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.
is
and ==
Feature | is (Identity) | == (Equality) |
---|---|---|
Purpose | Checks if two objects are the same instance in memory. | Checks if two objects have the same value. |
Comparison | Compares memory addresses. | Compares object values. |
Common Usage | Used with singletons (e.g., None ). | Used for general equality checks. |
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)
is
vs ==
is
when checking for identity (e.g., x is None
).==
when checking for equality of values.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
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
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