This question already has an answer here:
I am trying to add multiple 'or' clauses to a python if statement using list comprehension. My code is shown below. I would like to keep the list comprehension. In terms of pseudocode, the logic would simply be:
Alive_Beatles = each name that contains '(Beatle)' and either ('Paul', 'Yoko' or 'Ringo')
The code only returns Paul and skips Ringo and Yoko.
Names = ["John Lennon (Beatle)", "Paul McCartney (Beatle)", "Ringo Starr (Beatle)", "Yoko Ono (Beatle)", "Mick Jagger (Rolling Stone)", "Brian Jones (Rolling Stone)", "Alex Jones (na)", "Adam Smith (na)"]
Alive_Beatles = [n for n in Names if ("Beatle" and ("Paul" or "Ringo" or "Yoko")) in n]
print Alive_Beatles
This doesn't do what you expect because the expression
evaluates to
"Paul"
. Type it in at an interpreter prompt to confirm this.And even that only seems to work because
also evaluates to
"Paul"
.The most straightforward solution is to just list
But you could use
any
to get a bit closer to what you tried initially:You need to test each name explicitly if it's
in n
:Otherwise the
and
andor
use the truth value of you search strings (and each non-empty string is always True) and finally tests ifPaul in n
(the first truth value of theor
s).The documentation explicitly mentions this:
So
"Beatle" and (...)
evaluates according to (2) to the second argument because"Beatle"
is truthy and according to (1) it evaluates to the first argument of the chainedor
s:"Paul"
because it's also truthy.