[Python] elif in list comprehension conditionals

Discussão em 'Python' iniciado por Stack, Junho 11, 2025.

  1. Stack

    Stack Membro Participativo

    Consider this example:

    l = [1, 2, 3, 4, 5]

    for values in l:
    if values == 1:
    print('yes')
    elif values == 2:
    print('no')
    else:
    print('idle')


    Rather than printing the results, I want to use a list comprehension to create a list of results, like ['yes', 'no', 'idle', 'idle', 'idle'].

    How can we represent the elif logic in a list comprehension? Up until now, I have only used if and else in list comprehension, as in if/else in a list comprehension.

    Continue reading...

Compartilhe esta Página