Search code examples
pythonsyntaxoperator-precedence

in over multiple lists


I was recently confused by this

if 2 in ([1,2] or [3,4]) : print(True)
else: print(False)
#prints True
  1. or is a boolean operator so how can it be applied to lists?
  2. why does it work the same as if 2 in [1,2] or [3,4]?

Solution

    1. Use any()
    print(any(2 in x for x in [[1, 2], [3, 4]]))
    
    1. or is operates on any types, not just booleans. It returns the leftmost operand that's truthy, or False if none of the operands are truthy. So ([1, 2] or [3, 4]) is equivalent to [1, 2] because any non-empty list is truthy.

    In general, operators don't automatically distribute in programming languages like they do in English. x in (a or b) is not the same as x in a or x in b. Programming languages evaluate expressions recursively, so x in (a or b) is roughly equivalent to:

    temp = a or b
    x in temp