Object Comparison: == vs is

  • The == operator compares by checking for equality (the objects referred to by the variables are equal, i.e. have the same contents)
  • The is operator comparies identities (whether two variables are in fact pointing to the same identical object)

Example

>>> a = [1, 2, 3] 
>>> b = a
>>> a
[1, 2, 3] 
>>> b
[1, 2, 3]
>>> a == b 
True
>>> a is b 
True

a and b point to the same list object, as we assigned them earlier.

>>> c = list(a) # create an identical copy of the list a
>>> c
[1, 2, 3]
>>> a == c # should be true, as a and c have the same content
True
>>> a is c 
False
Previous
Next