Identity vs Equality in Python
This topic is extremely important if you are learning Python as a beginner.
Golden Rule
-
==→ compares values -
is→ compares memory identity
Example 1:
In the following example, even though values are the same,
a and b are different objects in memory.a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True
print(a is b) # False
Example 2:
In this example, a and b are equal and as well as identical. This is because Python reuses small integers to optimize memory usage which is known as Integer Interning.
a = 256
b = 256
print(a == b) # False
print(a is b) # True
Example 3:
The same logic applies to string values since Python reuses small string values to optimize memory usage as well.
a = "hello"
b = "hello"
print(a is b) # True
Example 4:
In the following example, the values are equal but they are different objects.
a = "".join(["he", "llo"])
b = "hello"
print(a is b) # False
Comments
Post a Comment