Skip to content Skip to sidebar Skip to footer

Unexpected Result From `in` Operator - 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 Fa

Solution 1:

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 isTrue

is treated as

(item inseq) 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) isTrue)

Click here for the docs.

Solution 2:

Your statement item in seq is True is internally evaluated as (item in seq) and (seq is True) as shown below

>>>print ((item in seq) and (seq isTrue))
False

(seq is True) is False and therefore your statement outputs False.

Solution 3:

The answer below is not correct. The comment explains it an i verified:

In [17]: item in (seq isTrue)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent calllast)
<ipython-input-17-4e7d6b2332d7>in<module>()
----> 1 item in (seq is True)

TypeError: argument of type 'bool' is not iterable


Previous answer I believe it is evaluating seq is True (which evaluates to the bool False), then evaluating item in False (which evaluates to False).

Presumably you mean print (item in seq) is True (which evaluates to True)?

Post a Comment for "Unexpected Result From `in` Operator - Python"