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?

1
  • 1
    It might be because of how python evaluates an expression. You might want to use print ((item in seq) is True)
    – worker_bee
    Commented Jul 19, 2017 at 4:23

3 Answers 3

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.

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.

5
  • Isn't that explained sufficiently in @Tim Peters answer?
    – t.m.adam
    Commented Jul 19, 2017 at 4: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.
    – Jagan N
    Commented Jul 19, 2017 at 4:43
  • @Beginner NO. Can't a question have two correct answers?
    – void
    Commented Jul 19, 2017 at 4: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. Commented Jul 19, 2017 at 4:45
  • 1
    Please don't take my comment the wrong way. I just wanted to encourage you to improve your answer.
    – t.m.adam
    Commented Jul 19, 2017 at 4: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)?

2
  • 2
    item in False raises a TypeError, as the right-hand value must be an iterable, which False is not. Commented Jul 19, 2017 at 4:56
  • changed answer. thanks Commented Jul 19, 2017 at 14:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.