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 a==b?
Advertisement
Answer
Am I right in assuming that
a==b in [c,d,e]is equivalent to(a==b) in [c,d,e]
No. Since both == and in are comparison operators, the expression
a == b in [c, d, e]
is equivalent to
(a == b) and (b in [c, d, e])
since all comparison operators have the same precedence but can be chained.
and therefore only really makes sense if
[c,d,e]is a list ofTrue/Falsevalues?
It can also make sense to check if a boolean value is contained in a list of integers. Since True is considered equivalent to 1, and False is considered equivalent to 0 (see The standard type hierarchy), the result of this check can even be True.