0

I feel like I've somehow misunderstood the fundamental concept of how the 'or' keyword works in Python.

I have the following code:

word = "aarrgh"

print(*[x for x in word if x == "a" or "r"])

and this is giving me:

a a r r g h

The same thing happens when using == or !=.

What am I missing here? I cant find anything online explaining this so sorry if this is something obvious.

martineau
  • 119,623
  • 25
  • 170
  • 301
Xexizy
  • 13
  • 1

1 Answers1

2

Your problem isn't specifically related to the comprehension. It's a question of how or and == works. x == "a" or "r" means (x == "a") or "r". You should use one of these instead.

print(*[x for x in word if x in ["a", "r"]])
print(*[x for x in word if x == "a" or x == "r"])
recursive
  • 83,943
  • 34
  • 151
  • 241