Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result from `in` operator - Python [duplicate]

Tags:

python

>>> item = 2
>>> seq = [1,2,3]
>>> print (item in seq)
True
>>> print (item in seq is True)
False

Why does the second print statement output False?

like image 436
John Gordon Avatar asked Jul 19 '17 04:07

John Gordon


1 Answers

in and is are comparison operators in Python, the same in that respect as, say, < and ==. In general,

expr1 <comparison1> expr2 <comparison2> expr3

is treated as

(expr1 <comparison1> expr2) and (expr2 <comparison2> expr3)

except that expr2 is evaluated only once. That's why, e.g.,

0 <= i < n

works as expected. However, it applies to any chained comparison operators. In your example,

item in seq is True

is treated as

(item in seq) and (seq is True)

The seq is True part is False, so the whole expression is False. To get what you probably intended, use parentheses to change the grouping:

print((item in seq) is True)

Click here for the docs.

like image 160
Tim Peters Avatar answered Sep 16 '22 15:09

Tim Peters