Rob Truxal Rob Truxal - 4 months ago 19
Python Question

how to conceptualize grouping in python logic statments

No idea why this happens. Can anyone explain?

>>> foo = ['a', 'b', 'c']
>>> bar = [1, 2, 3]

>>> 'a' in (foo or bar)
>>> 'a' in (bar or foo)

I understand that python reads left to right, and that I should write out

>>> 'a' in foo or 'a' in bar

but what is going on in my test example? Why do I get True and False respectively?


Since foo is true, foo or bar returns foo:

>>> foo = ['a', 'b', 'c']
>>> bar = [1, 2, 3]
>>> (foo or bar)
['a', 'b', 'c']

In a logical-or statement, evaluation can stop when the first true quantity is found. So, once python evaluates foo as true, there is no need for it to consider bar. Further, in a logical-or statement, python does not return True: it returns the first item that evaluates to True.

Likewise, since bar is true, bar or foo returns bar. Order matters:

>>> bar or foo
[1, 2, 3]

As another example:

>>> False or 3 or 6