Why does string equality not working in this Python code as expected?

Why does string equality not working in this Python code as expected?

You need to use == not is. is checks for object identity not equality.

e.g.

Lets say you have foo and bar:

>>> foo = green eggs and ham
>>> bar = green eggs and ham
>>> foo is bar
>>> False
>>> foo == bar
>>> True

On my machine:

>>> id(foo)
>>> 52008832 
>>> id(bar)
>>> 52010560

Now, check this out:

>>> foobar = bar
>>> foobar is bar
>>> True

This is true because weve aliased the variable foobar to point to bar which is a reference. Clearly, they reference the same location under this aliasing. Hence, is returns True.

More interestingly, consider two ints. This will only work for small ints (-5, 256).

>>> foo = 123
>>> bar = 123
>>> foo is bar
>>> True
>>> id(foo)
>>> 1993000432 # == id(bar)

ints (-5, 256) are cached and so ints within this range will eval to true using is for comparing object identity.

I have never used is in my entire history with Python (That might be because I am still having trouble wrapping my head around OOP). Just use the regular equality operator ==.

Why does string equality not working in this Python code as expected?

Leave a Reply

Your email address will not be published. Required fields are marked *