Data Model

Equality and Identity

== compares values, while is compares object identity.

Equal containers can be different objects. == compares list contents, while is checks whether both names refer to the same list object.

Source

left = [1, 2, 3]
right = [1, 2, 3]
print(left == right)
print(left is right)

Output

True
False
IS + ==ab[1,2]== ONLYab[1,2][1,2]
Two names can share one object (`is` and `==` both true) or hold two equal-but-distinct objects (only `==` true).

Identity matters when objects are mutable. same is another name for left, so mutating through one name changes the object seen through the other.

Source

same = left
same.append(4)
print(left)
print(same is left)

Output

[1, 2, 3, 4]
True

Use is for singleton identity checks such as None. This asks whether the value is the one special None object.

Source

value = None
print(value is None)

Output

True

is for integers is unreliable because CPython caches small integers (roughly -5 to 256) but not larger ones. Two equal large integers can be different objects. Use == for value comparisons; reserve is for singletons.

Source

small_a = 100
small_b = 100
print(small_a is small_b)

big_a = int("1000")
big_b = int("1000")
print(big_a is big_b)
print(big_a == big_b)

Output

True
False
True

Notes

See also

Run the complete example

Example code

Expected output

True
False
[1, 2, 3, 4]
True
True
True
False
True

Execution time appears here after you run the example.