Learning Sections show
'is' vs '==' in Python
In Python, both is
and ==
are used for comparisons, but they serve different purposes.
1. ==
(Equality Operator)
The ==
operator checks if the values of two objects are equal. It evaluates to True
if the objects referred to have the same value.
Example:
# Using == to check equality
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # Output: True
2. is
(Identity Operator)
The is
operator checks if two variables point to the same object in memory. It evaluates to True
if the objects referred to are the same.
Example:
# Using is to check identity
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # Output: False
c = a
print(a is c) # Output: True
3. Key Differences
==
checks for value equality. It returnsTrue
if the values of the two objects are the same.is
checks for reference equality. It returnsTrue
if both variables point to the same object (i.e., same memory location).
Understanding the difference between is
and ==
is crucial when comparing objects in Python, especially when dealing with mutable types like lists and dictionaries.