[Python] Sort list while pushing None values to the end

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have a homogeneous list of objects with None, but it can contain any type of values. Example:

    >>> l = [1, 3, 2, 5, 4, None, 7]
    >>> sorted(l)
    [None, 1, 2, 3, 4, 5, 7]
    >>> sorted(l, reverse=True)
    [7, 5, 4, 3, 2, 1, None]


    Is there a way without reinventing the wheel to get the list sorted the usual python way, but with None values at the end of the list, like that:

    [1, 2, 3, 4, 5, 7, None]


    I feel like here can be some trick with "key" parameter

    Continue reading...

Compartilhe esta Página