You can also use an if-else in a list comprehension in Python. Since in a comprehension, the first thing we specify is the value to put in a list, this is where we put our if-else.
List comprehension works with string lists also. The following creates a new list of strings that contains 'a'. Above, the expression if 'a' in s returns True if an element contains a character 'a'.
You got the order wrong. The if
should be after the for
(unless it is in an if-else
ternary operator)
[y for y in a if y not in b]
This would work however:
[y if y not in b else other_value for y in a]
You put the if
at the end:
[y for y in a if y not in b]
List comprehensions are written in the same order as their nested full-specified counterparts, essentially the above statement translates to:
outputlist = []
for y in a:
if y not in b:
outputlist.append(y)
Your version tried to do this instead:
outputlist = []
if y not in b:
for y in a:
outputlist.append(y)
but a list comprehension must start with at least one outer loop.
list comprehension formula:
[<value_when_condition_true> if <condition> else <value_when_condition_false> for value in list_name]
thus you can do it like this:
[y for y in a if y not in b]
Only for demonstration purpose : [y if y not in b else False for y in a ]
This is not a lambda function. It is a list comprehension.
Just change the order:
[ y for y in a if y not in b]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With