List comprehension with condition

Question:

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.

Asked By: selurvedu

||

Answers:

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)

Answered By: Joran Beasley

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.

Answered By: Jan Vlcinsky