16
>>> 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?

cs95
  • 379,657
  • 97
  • 704
  • 746
John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • 1
    It might be because of how python evaluates an expression. You might want to use `print ((item in seq) is True)` – worker_bee Jul 19 '17 at 04:23

3 Answers3

27

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.

Tim Peters
  • 67,464
  • 13
  • 126
  • 132
3

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 is True))
False

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

JSN
  • 2,035
  • 13
  • 27
  • Isn't that explained sufficiently in @Tim Peters answer? – t.m.adam Jul 19 '17 at 04:40
  • @t.m.adam - We both answered more or less at the same time. If his answer explains this in more detailed way, let me delete this answer. – JSN Jul 19 '17 at 04:43
  • @Beginner NO. Can't a question have two correct answers? – void Jul 19 '17 at 04:45
  • @Beginner I don't see any harm in leaving your answer. Although you shouldn't lose the rep you gained for this question, if you delete. – Paul Rooney Jul 19 '17 at 04:45
  • 1
    Please don't take my comment the wrong way. I just wanted to encourage you to improve your answer. – t.m.adam Jul 19 '17 at 04:52
1

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

In [17]: item in (seq is True)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<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)?

travelingbones
  • 7,919
  • 6
  • 36
  • 43