Difference Between == and is in Python
Difference Between == and is in Python
In Python, == and is are both comparison operators, but they serve different purposes.
1. == (Equality Operator)
Example:
a = [1, 2, 3]
b = [1, 2, 3]
2. is (Iden ty Operator)
Checks whether two objects refer to the same memory loca on.
Example:
Python interns small integers and short strings for memory op miza on.
This means numbers between -5 to 256 and certain strings may share the same memory
address.
a = 100
b = 100
x = 1000
y = 1000
Large numbers are not interned, so different variables may have different memory
loca ons.
s1 = "hello"
s2 = "hello"
s3 = "hello world"
s4 = "hello world"
Short strings are cached and may share the same memory.
Longer strings are not always interned, so they may have different memory
loca ons.
4. When to Use == vs is
True if x is
is None Checking if a variable is None x is None
None
5. Key Takeaways
Immutable objects (small integers, short strings) may be interned, so is can return
True.
In Python, None is a special singleton object that represents the absence of a value. It is
not the same as 0, False, or an empty string ("").
The correct way to check if a variable is None is by using the iden ty operator is, not ==.
is checks iden ty, ensuring that the variable actually refers to the singleton None
object.
== checks value, which can lead to unexpected behavior if an object overrides ==.
Correct way:
x = None
if x is None:
x = None
print("x is None")
Using == might work, but it is not recommended because a class can override == in
an unexpected way.
def check_value(value):
if value is None:
else:
print(f"Value is {value}")
def fetch_data(data=None):
if data is None:
return data
Using data = None avoids using mutable default arguments like [], which can cause
bugs.
is not None helps remove None values while keeping 0, False, or "".
If a class overrides ==, then using == None might not behave as expected.
Example:
class Example:
obj = Example()
4. Key Takeaways
Always use is None for checking None values.
Avoid == None because it can be overridden.
Use is not None when filtering non-None values.
Using None as a default argument is a good prac ce in func ons.
Would you like an example of a real-world scenario where using is None prevents a bug?