pythonif-statementlist-comprehensiongenerator-expression

List comprehension with condition


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.


Solution

  • 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)