pythonlistlist-comprehension

if/else in a list comprehension


How do I convert the following for-loop containing an if/else into a list comprehension?

results = []
for x in xs:
    results.append(f(x) if x is not None else '')

It should yield '' if x is None, and otherwise f(x). I tried:

[f(x) for x in xs if x is not None else '']

but it gives a SyntaxError. What is the correct syntax?


See Does Python have a ternary conditional operator? for info on ... if ... else ....
See List comprehension with condition for omitting values based on a condition: [... for x in xs if x cond].
See `elif` in list comprehension conditionals for elif.


Solution

  • You can totally do that. It's just an ordering issue:

    [f(x) if x is not None else '' for x in xs]
    

    In general,

    [f(x) if condition else g(x) for x in sequence]
    

    And, for list comprehensions with if conditions only,

    [f(x) for x in sequence if condition]
    

    Note that this actually uses a different language construct, a conditional expression, which itself is not part of the comprehension syntax, while the if after the for…in is part of list comprehensions and used to filter elements from the source iterable.


    Conditional expressions can be used in all kinds of situations where you want to choose between two expression values based on some condition. This does the same as the ternary operator ?: that exists in other languages. For example:

    value = 123
    print(value, 'is', 'even' if value % 2 == 0 else 'odd')