Reputation: 501
Suppose I have a list a = [0, 1, 2]
.
I know that I can use a list comprehension like so, to get a list where the values are doubled:
>>> b = [x*2 for x in a]
>>> b
[0, 2, 4]
How can I make it so that the list comprehension ignores 0
values in the input list, so that the result is [2, 4]
?
My attempt failed:
>>> b = [x*2 if x != 0 else None for x in a]
>>> b
[None, 2, 4]
See if/else in a list comprehension if you are trying to make a list comprehension that uses different logic based on a condition.
Upvotes: 14
Views: 36694
Reputation: 44142
Following the pattern:
[ <item_expression>
for <item_variables> in <iterator>
if <filtering_condition>
]
we can solve it like:
>>> lst = [0, 1, 2]
>>> [num
... for num in lst
... if num != 0]
[1, 2]
It is all about forming an if condition testing "nonzero" value.
Upvotes: 8
Reputation: 114088
b = [x*2 for x in a if x != 0]
if you put your condition at the end you do not need an else (infact cannot have an else there)
Upvotes: 23