Comparison in Python

From Exterior Memory
Jump to: navigation, search

Python has two comparison functions:

a == b
a is b

However, they are not the same.

a == b tests object equivalence, and is equivalent to cmp(a,b) or a.__cmp__(b).

a is b tests object equivalence, and is equivalent to id(a) == id(b).

Caveat

You are recommended to use a == b. In particular, you should never use a is b for string comparison. The reason is that Python employs string caching, which behaves differently for different lengths of strings, or whether you are running Python in interactive mode or not. For example, the following code resulted in False in interactive mode, but in True in non-interactive mode on my computer:

a = "some string"
b = "some string"
print (a is b)   # Bad practice, use a == b instead!