how to sort 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.


n = ['aaa', 'bbb', 'ccc', 'dddd', 'dddl', 'yyyyy']

for i in reversed(sorted(n, key=len)):
    print i

yyyyy dddl dddd ccc bbb aaa

for i in sorted(n, key=len, reverse=True):
     print i

yyyyy dddd dddl aaa bbb ccc


-Sort your list by alpha order, then by length.

See the following exmple:

>>> coursesList = ["chemistry","physics","mathematics","art"]
>>> sorted(coursesList,key=len)
['art', 'physics', 'chemistry', 'mathematics']
>>> coursesList.append("mopsosa")
>>> sorted(coursesList,key=len)
['art', 'physics', 'mopsosa', 'chemistry', 'mathematics']
>>> coursesList.sort()
>>> sorted(coursesList,key=len)
['art', 'mopsosa', 'physics', 'chemistry', 'mathematics']

Tags:

Python

Sorting