Python - == vs is

Introduction

Python comparisons inspect all parts of compound objects until a result can be determined.

When nested objects are present, Python automatically traverses data structures to apply comparisons.

The first difference found determines the comparison result.

Demo

L1 = [1, ('a', 3)]           # Same value, unique objects 
L2 = [1, ('a', 3)] 
print( L1 == L2, L1 is L2 )           # Equivalent? Same object?
# from w w  w  . ja va2  s .c o  m

Result

Here, L1 and L2 are assigned lists that are equivalent but distinct objects.

The == operator tests value equivalence. Python performs an equivalence test, comparing all nested objects recursively.

The is operator tests object identity.

Python tests whether the two are really the same object, i.e., live at the same address in memory.

Here, L1 and L2 pass the == test since they have equivalent values because all their components are equivalent.

It fails the is check since they reference two different objects, and hence two different pieces of memory.

Demo

S1 = 'test' 
S2 = 'test' 
print( S1 == S2, S1 is S2 )

Result

Here, we should have two distinct objects that happen to have the same value: == should be true, and is should be false.

But Python internally caches and reuses some strings as an optimization, there really is just a single string 'test' in memory, shared by S1 and S2.

The is identity test reports a true result.

To trigger the normal behavior, we need to use longer strings:

Demo

S1 = 'a longer string' 
S2 = 'a longer string' 
print( S1 == S2, S1 is S2 )

Result

The == operator is what you will want to use for almost all equality checks.

Less, equal, greater

Demo

L1 = [1, ('a', 3)] 
L2 = [1, ('a', 2)] 
print( L1 < L2, L1 == L2, L1 > L2 )        # Less, equal, greater: tuple of results
# w w w . j  av  a  2  s. co m

Result

Here, L1 is greater than L2 because the nested 3 is greater than 2.

Related Topics