How to sort a list by length of string followed by alphabetical order?

You can do it in two steps like this:

the_list.sort() # sorts normally by alphabetical order
the_list.sort(key=len, reverse=True) # sorts by descending length

Python’s sort is stable, which means that sorting the list by length leaves the elements in alphabetical order when the length is equal.

You can also do it like this:

the_list.sort(key=lambda item: (-len(item), item))

Generally you never need cmp, it was even removed in Python3. key is much easier to use.

Leave a Comment