pythonstringsorting

Sort a list of tuple by first element with blank values at the end


I have this list:

list = (('',''),('1','products'),('3','test'),('2','person'))

When I use sorted(list) it gives me

list = (('',''),('1','products'),('2','person'),('3','test'))

I would like to keep this order but just putting the blank values at the end, like this:

list = (('1','products'),('2','person'),('3','test'),('',''))

Solution

  • Use a key function that adds an element at the beginning of the tuple that indicates whether the original tuple has an empty first element.

    my_list = (('',''),('1','products'),('3','test'),('2','person'))
    sorted(my_list, key=lambda x: (x[0] == '', *x))
    

    Result:

    [('1', 'products'), ('2', 'person'), ('3', 'test'), ('', '')]