Unexpected result of the `in` operator - Python

advertisements

This question already has an answer here:

  • Multiple repeated `in` keyword [duplicate] 3 answers
>>> 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?


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.