[Python] if/else in a list comprehension

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página