Why Does This Not Work As An Array Membership Test?
>>> 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 co
Solution 1:
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
.
Post a Comment for "Why Does This Not Work As An Array Membership Test?"