0

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?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Emil
  • 1,531
  • 3
  • 22
  • 47

1 Answers1

1

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']
S4eed3sm
  • 1,398
  • 5
  • 20