-1

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]?
lineage
  • 792
  • 1
  • 8
  • 20
  • That condition should actually read `if any(2 in sub for sub in [[1,2], [3,4]]):` – Cory Kramer Feb 18 '20 at 17:47
  • To answer your other question: https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false a non-empty list is considered "truthy" so `[1,2] or [3,4]` evaluates to `True` – Cory Kramer Feb 18 '20 at 17:48

2 Answers2

1
  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
Barmar
  • 741,623
  • 53
  • 500
  • 612
1
  • Both statement are different.
  • In first case python will first run 2 in [1,4] its False so now it will check for bool([1,3]) and its True so it prints 1.
  • But for second case what happening is first ([1,4] or [1,3]) is executing and this return first non-empty list. And so it will return [1,4] but 2 is not in list so nothing gets printed.
  • Its all about execution order.
  • Look at two more examples. Specially last example. ([1,4] or [2,4]) will return [1,4] and 2 is not in [1,4]. Now it will not check in second list [2,4]. If that's you want this is not the right way to do it. Use any
>>> if 2 in [1,4] or [1,3]: # True
...     print(1)
...
1
>>> if 2 in ([1,4] or [1,3]): # False
...     print(1)
...
>>> if 2 in [1,4] or []: # False
...     print(1)
...
>>> if 2 in ([1,4] or [2,4]): # False!!
...     print(1)
...
Poojan
  • 3,366
  • 2
  • 17
  • 33