Python gotcha moment


>>> -1 is True
False
>>> (not -1) is True
False


Something to remember when messing with functions which can return negative numbers.

Update: Solution here is to use not not syntax

>>> (not not -1) is True
True
>>> not (not not -1) is True
False
>>> (not not 1) is True
True
>>> not (not not 1) is True
False

3 yorum:

havan said...

>>> not -1 is True
True
>>> (not -1) is True
False

I don't get it. :/

cartman said...

Well because "is" operator have precedence over "not".

>>> not (-1 is True)
True

BlueRaja said...

Sent this to my Python-expert friend; your post makes sense, since -1 and True *are* different objects:

>>> 1 is True
False
>>> bool(1) is True
True
>>> -1 is True
False
>>> bool(-1) is True
True