2
>>> 5 in [1, 2, 3, 4] == False
False

I get that this is a bizarre way to test membership, and that

>>> 5 not in [1, 2, 3, 4]
True

is the "correct" way. What confuses me is that its behavior is different from both

>>> (5 in [1, 2, 3, 4]) == False
True

and

>>> 5 in ([1, 2, 3, 4] == False)
TypeError ...

Have I missed something obvious? (Tested in Python 2.7 and Python 3.4).

To clarify, I understand the last three snippets. I am asking about the behavior of the first snippet, and why it is different.

7
  • 3
    This is definitely a dupe, but I can't find an appropriate dupe candidate. Commented Dec 6, 2016 at 3:15
  • OK... then how do you know it's a dupe?
    – Ian Kuehne
    Commented Dec 6, 2016 at 3:18
  • @user2357112 - This seems close. Commented Dec 6, 2016 at 3:19
  • @user2357112 - Found a good one. Commented Dec 6, 2016 at 3:20
  • @TigerhawkT3: The question is a dupe, but the answers to that one suck. None of them explain anything. Commented Dec 6, 2016 at 3:21

1 Answer 1

4

This is a chained comparison. You may have known that you can do

1 < 2 < 3

in Python, and it's equivalent to (1 < 2) and (2 < 3). (Or maybe you didn't. Now you know.) Well, the same thing applies to in and ==.

5 in [1, 2, 3, 4] == False

is equivalent to

(5 in [1, 2, 3, 4]) and ([1, 2, 3, 4] == False)

Since [1, 2, 3, 4] is not equal to False, the whole expression evaluates to False.

5
  • Awesome! I know about chained comparisons; I didn't realize they applied to in. Good answer!
    – Ian Kuehne
    Commented Dec 6, 2016 at 3:20
  • This is such a common wat. I actually tried to get in and not in documented as comparison operators, since they are literally defined as comparisons in the grammar, but did not get much support on bugs.python.org
    – wim
    Commented Dec 6, 2016 at 3:42
  • I was thinking about making the lack of documentation a bug report too; I guess it's a lost cause. Any idea why it's a comparison operator? I can't think of any case where this behavior is useful.
    – Ian Kuehne
    Commented Dec 6, 2016 at 4:49
  • @IanKuehne: I'm guessing it was just convenient for the implementation to stick them in with the other comparison operators, and they didn't care too much about the chaining behavior. Commented Dec 6, 2016 at 5:12
  • The last sentence is wrong. Already 5 in [1, 2, 3, 4] is False, and and short-circuits, so [1, 2, 3, 4] == False doesn't even get evaluated at all. Commented Jul 29, 2022 at 3:20

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