Home > other >  Sort elements in list based on length first and alphabetical order second
Sort elements in list based on length first and alphabetical order second

Time:01-08

I have a list with strings. Now, I want to sort the elements in this list based on string length.

proxy_list = ['my', 'list', 'looks', 'like', 'this']

My desired output looks as follows:

desired_output = ['my','like','list','this','looks']

The code below sorts the list based on length, but not on alphabetical order:

print(sorted(proxy_list, key=len))
>>> ['my', 'list', 'like', 'this', 'looks'] 

How can I sort a list with string based on two things?

CodePudding user response:

use key argument of sorted function. convert each element to a tuple of priority. here (len(s), s), this means len(s) have more priority to s.

proxy_list = ['my', 'list', 'looks', 'like', 'this']
print(sorted(proxy_list, key=lambda s: (len(s), s)))
#>>> ['my', 'like', 'list', 'this', 'looks']
  •  Tags:  
  • Related