String comparison in Python: is vs. ==
Posted
by Coquelicot
on Stack Overflow
See other posts from Stack Overflow
or by Coquelicot
Published on 2010-06-07T08:31:49Z
Indexed on
2010/06/07
9:22 UTC
Read the original article
Hit count: 212
I noticed a Python script I was writing was acting squirrelly, and traced it to an infinite loop, where the loop condition was "while line is not ''". Running through it in the debugger, it turned out that line was in fact ''. When I changed it to != rather than 'is not', it worked fine.
I did some searching, and found this question, the top answer to which seemed to be just what I needed. Except the answer it gave was counter to my experience. Specifically, the answerer wrote:
For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.
I double-checked the type of the variable, and it was in fact of type str (not unicode or something). Is his answer just wrong, or is there something else afoot?
Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values? I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.
© Stack Overflow or respective owner