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.
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.
This question is related to
python
string
comparison
equality
I would like to show a little example on how is
and ==
are involved in immutable types. Try that:
a = 19998989890
b = 19998989889 +1
>>> a is b
False
>>> a == b
True
is
compares two objects in memory, ==
compares their values. For example, you can see that small integers are cached by Python:
c = 1
b = 1
>>> b is c
True
You should use ==
when comparing values and is
when comparing identities. (Also, from an English point of view, "equals" is different from "is".)
The logic is not flawed. The statement
if x is y then x==y is also True
should never be read to mean
if x==y then x is y
It is a logical error on the part of the reader to assume that the converse of a logic statement is true. See http://en.wikipedia.org/wiki/Converse_(logic)
See This question
Your logic in reading
For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.
is slightly flawed.
If is
applies then ==
will be True, but it does NOT apply in reverse. ==
may yield True while is
yields False.
Source: Stackoverflow.com