[Python] Efficiently filtering out 'None' items in a list comprehension in which a function is...

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

  1. Stack

    Stack Membro Participativo

    I have a list comprehension that calls a function which potentially returns None.

    f = lambda x: x if x < 3 else None
    l = [f(x) for x in [1,2,3,4]] # [1, 2, None, None]


    I'd like to have the list comprehension as above, without the None entries.

    What's a more efficient way to do the following, without creating the additional overhead, and while retaining the efficiency of the list comprehension?

    filter(None, l) # [1, 2]

    Continue reading...

Compartilhe esta Página