Search notes:

Python: list.sort()

The method sort() on a list sorts its elements in place (that is, it does not return or evaluate to something):
L = [ 'one', 'two', 'three', 'four', 'five', 'six', 'seven' ]
L.sort()
print(L)
#
#  ['five', 'four', 'one', 'seven', 'six', 'three', 'two']
Github repository about-Python, path: /types/list/sort/simple.py
Because list.sort() sorts a list in place, it cannot be used in in a in a for e in L.sort(): … statement. Such a for loop is possible, however, with for e in sorted(L): ….

Sorting a list based on a characteristic of its elements

With the key parameter of list.sort and a lambda expression, it is possible to sort the elements of a list based on an arbitrary characteristic of its element.
The following example sorts the words in a list in order of the length of the words:
words = [ 'appple', 'car', 'quit', 'oh', 'thunderstorm', 'academy' ]

words.sort(key = lambda w: len(w))

print(words)
#
#  ['oh', 'car', 'quit', 'appple', 'academy', 'thunderstorm']
Github repository about-Python, path: /types/list/sort/expression.py
Compare with the same functionality in sorted()

See also

The built-in function sorted.

Index