1

No idea why this happens. Can anyone explain?

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

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

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?

Rob Truxal
  • 5,856
  • 4
  • 22
  • 39
  • What is most important thing to understand is the expression in the parens is evaluated first and the in check is done on the result of that. Without the parens `'a' in bar or foo -> ['a', 'b', 'c'] ` – Padraic Cunningham Sep 20 '16 at 23:13

2 Answers2

1

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
3
John1024
  • 109,961
  • 14
  • 137
  • 171
1

The reason lies in how a or b works in Python. If a is having value or is True, a will be returned else value of b is returned. In your case:

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

If you want to check the values in both the list, firstly make a single list with elements from both list by using + as:

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

Then you can make your condition as:

>>> 'a' in (foo + bar)
True
>>> 'a' in (bar + foo)
True

Alternatively, you can also do it using or (without concatenating lists) as:

>>> 'a' in foo or 'a' in bar
True
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126