Is vs == Python
is
vs ==
in Python
Python provides two different operators for comparison: is
and ==
. While they might seem similar, they serve distinct purposes.
1. ==
(Equality Operator)
The ==
operator checks if the values of two objects are equal. It does not care whether they are stored at the same memory location.
Example:
pythonCopyEditx = [1, 2, 3]
y = [1, 2, 3]
print(x == y) # Output: True
Here, x
and y
have the same values, so ==
returns True
, even though they are different objects in memory.
Key Points:
- Compares values.
- Works with numbers, strings, lists, dictionaries, etc.
- Returns
True
if the values are the same, regardless of memory location.
2. is
(Identity Operator)
The is
operator checks whether two variables refer to the same object in memory.
Example:
pythonCopyEditx = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # Output: False
Even though x
and y
have the same values, they are stored separately in memory, so is
returns False
.
Key Points:
- Compares memory addresses, not values.
- Returns
True
only if both variables point to the exact same object. - Often used for checking singleton objects like
None
,True
, andFalse
.
3. Key Differences:
Feature | == (Equality) | is (Identity) |
---|---|---|
Compares | Values | Memory locations |
Works on | Numbers, lists, strings, etc. | Objects, singletons (None , True , False ) |
Output | True if values match | True if both variables point to the same object |
4. Common Pitfalls
Using is
Instead of ==
pythonCopyEditx = 1000
y = 1000
print(x is y) # Output: False (Different memory locations)
For large integers, Python stores them separately, so is
does not work.
Incorrect Use of ==
for None
pythonCopyEditx = None
if x == None: # Avoid this
print("Incorrect way to check for None")
✅ Correct approach:
pythonCopyEditif x is None:
print("Correct way to check for None")
Use is
for None
comparisons, as per Python’s best practices.
5. When to Use is
vs ==
- ✅ Use
==
when checking if values are equal. - ✅ Use
is
when checking if two variables refer to the same object. - ✅ Prefer
is
for checkingNone
,True
, orFalse
.
6. Conclusion
==
checks for value equality.is
checks for object identity (same memory location).- Misusing them can lead to subtle bugs, so understanding their difference is crucial in Python programming.