-1

When I try to print a conditional in Python, it doesn't return the actual result but the first string in the print statement.

letters = ['a', 'b', 'c', 'd', 'e']

print('a' or 'b' in letters)

This should print "True", but it instead prints

a

Why does this happen, and do you have anything to fix this? Thanks

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 2
    Common misunderstanding in python. Python parses that as `'a' or ('b' in letters)` and since `or` evaluates to the first truthy thing it sees, it returns 'a'. You want ` 'a' in letters or 'b' in letters` – Frank Yellin Dec 29 '20 at 23:46
  • Does this answer your question? [Simplest way to check if multiple items are (or are not) in a list?](https://stackoverflow.com/questions/22673770/simplest-way-to-check-if-multiple-items-are-or-are-not-in-a-list), [or command in if statement not working properly](https://stackoverflow.com/q/62286603/4518341) – wjandrea Dec 30 '20 at 00:25

2 Answers2

2

or is not distributed over in, so it's being parsed as

print('a' or ('b' in letters))

Since 'a' is a truthy value, that's the value of the expression. You need to test each one separately.

print('a' in letters or 'b' in letters)

If you have a list of strings you want to check, you can use any()

test = ['a', 'b']
print(any(t in letters for t in test))
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

It happens because of the precedence of operators: in comes before or, so what you have is the same as 'a' or ('b' in letters). Then or stops at the first value that is True, and bool('a') is True, so you get 'a'.

For what you want, try either:

print(bool({'a', 'b'}.intersection(letters)))

# or

print('a' in letters or 'b' in letters)
Pierre D
  • 24,012
  • 7
  • 60
  • 96
  • I think operator precedence is a red herring here. `('a' or 'b') in letters` is also not what OP wants. It'll work in this case, but only because `'a' or 'b'` -> `'a'`. On the other hand, `('z' or 'b') in letters` would fail. – wjandrea Dec 30 '20 at 00:33