0

I have a very strange thing happening where two lists which are clearly equal are not being considered equal by Python. From here you can see the IPython console output of an element of a dictionary I am working with:

In [251]: saveDict['data']['hpSH']['manifold_type'] Out[251]: ['duct', 'pipe']

Then when I go to check if this same dictionary element is equal to the list ['duct', 'pipe'], it says it is not:

In [252]: ['duct', 'pipe'] is saveDict['data']['hpSH']['manifold_type'] Out[252]: False

However, using "==" instead of "is" results in a True output in the console.

I discovered this because it is messing up other parts of my code and not doing the same calculations with saveDict['data']['hpSH']['manifold_type'] as it is with ['duct', 'pipe']. To give you more backstory, saveDict is coming from a saved file made by cPickle. Here is more on the environment I am working with:

Windows 10, Python 2.7.12 :: Anaconda 4.1.1 (32-bit), Spyder 2 IDE

1 Answers1

4

You should compare lists for equality with ==, not is

The is operator is for comparing object IDs in the Python runtime; it asks, literally, are the two the same object. Observe this example:

In [13]: ['a', 'b'] == ['a', 'b']
Out[13]: True

In [14]: ['a', 'b'] is ['a', 'b']
Out[14]: False

Examining the ids helps:

In [19]: id(['a', 'b'])
Out[19]: 140365516758984

In [20]: id(['a', 'b'])
Out[20]: 140365515846360

Note: two calls of id on the same list (same values) produces different IDs, since these are different objects.


For more background see this SO discussion

Community
  • 1
  • 1
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412