Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

key sort of strings

  • key

  • len

  • Another example for using a key.

  • To sort the list according to length

animals = ['chicken', 'cow', 'snail', 'elephant']
print(animals)

animals.sort()
print(animals)

animals.sort(key=len)
print(animals)

animals.sort(key=len, reverse=True)
print(animals)

Output:

['chicken', 'cow', 'snail', 'elephant']
['chicken', 'cow', 'elephant', 'snail']
['cow', 'snail', 'chicken', 'elephant']
['elephant', 'chicken', 'snail', 'cow']