The difference between is and==in Python

Published on Aug. 22, 2023, 12:16 p.m.

In Python, is is used for identity comparison, while == is used for value comparison.

is checks if two objects are the same object, meaning they have the same memory address. On the other hand, == compares the values of the objects to see if they are equal.

For example:

a = [1, 2, 3]
b = a
c = [1, 2, 3]

print(a is b)  # True, a and b are the same object
print(a is c)  # False, a and c are not the same object
print(a == c)  # True, a and c have the same values

Note that for some objects in Python, like integers and small strings, they may be small enough to be interned and reused by the interpreter, so is may return True even when values are different. However, this is an implementation detail and should not be relied on. In general, it’s best to use == for value comparison unless you specifically need to check object identity.

Tags:

related content