This Content is from Stack Overflow. Question asked by KIAaze
I just came across some python code with the following statement:
if a==b in [c,d,e]: ...
It turns out that:
>>> 9==9 in [1,2,3] False >>> 9==9 in [1,2,3,9] True >>> (9==9) in [1,2,3,9] True >>> 9==(9 in [1,2,3,9]) False >>> True in [1,2,3,9] True >>> True in  False >>> False in  False >>> False in [1,2,3] False
Am I right in assuming that
a==b in [c,d,e] is equivalent to
(a==b) in [c,d,e] and therefore only really makes sense if
[c,d,e] is a list of True/False values?
And in the case of the code I saw
b is always in the list
[c,d,e]. Would it then be equivalent to simply using
Just to throw another factor into the mix, operator chaining needs to be kept in mind as well:
Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c … y opN z is equivalent to a op1 b and b op2 c and … y opN z, except that each expression is evaluated at most once.
The docs there specify "comparison operators", but later down is the addition:
Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.
9==9 in [1,2,3,9] is confusingly the same as
9==9 and 9 in [1, 2, 3, 9].
This Question was asked in StackOverflow by KIAaze and Answered by Carcigenicate It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.