Is vs Equality#
The main pitfall when using is vs == in Python is that they test for
different things:
ischecks for object identity (if two variables point to the exact same object in memory)==checks for value equality (if two objects have the same value)
# Example 1: Integers
a = 1000
b = 1000
print(a == b) # True
print(a is b) # False
# Example 2: Small integers
x = 5
y = 5
print(x == y) # True
print(x is y) # True
# Example 3: Lists
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2) # True
print(list1 is list2) # False
# Example 4: Strings
str1 = "hello"
str2 = "hello"
print(str1 == str2) # True
print(str1 is str2) # True
# Example 5: None
print(None == None) # True
print(None is None) # True
True
False
True
True
True
False
True
True
True
True
Why so weird, let’s explain them.
For large integers,
==returnsTruebecause the values are the same, butisreturnsFalsebecause Python creates separate objects for larger integers.For small integers (-5 to 256), Python often reuses the same object for optimization, so both
==andisreturnTrue.For lists with the same content,
==returnsTruebecause the values are equal, butisreturnsFalsebecause they are distinct objects in memory.For strings, Python often interns (reuses) string literals, so both
==andismight returnTrue. However, this behavior isn’t guaranteed and can vary between Python implementations.For
None, both==andisalways returnTruebecauseNoneis a singleton object in Python.
The main pitfall occurs when programmers use is to compare values, expecting
it to behave like ==. This can lead to unexpected results, especially with
numbers, strings, or custom objects.
So the best practices are:
Use
==for value comparisons.Use
isonly for comparing toNoneor when you explicitly want to check for object identity.
None Is A Singleton Object#
None is a singleton object in Python, meaning there is only one instance of
it in memory. This is why None == None and None is None both evaluate to
True.
p = None
q = None
print(p == q) # True
print(p is q) # True
True
True