Sorting (Python)

There are two main built-in sorting functions in Python.

  1. sorted(iterable, key: function = None, reverse=False) -> iterable
  2. [iterable].sort(key: function = None, reverse=False) -> None

sorted will return a new sorted version of the iterable. sort will sort the iterable in place.

Arguments

iterable can be any iterable: list, tuple, or set.

The key keyword is used when you don't want to sort by comparing two items with <. You can pass in any function that can take each iterable item as an argument (e.g. ['a', 'b', 'c'] you could use key=str.upper). Also useful is to use lambdas for more complex comparisons (e.g. [[1,2,3], [4,5,6]] you could use lambda x: x[2] to sort using the 3rd item in each sublist).

reverse will sort each comparison as if the comparison was done in reverse. For instance, if you set your key to be the default <, using reverse=True will sort as if it were running >.

References

  1. https://docs.python.org/3/howto/sorting.html

Last modified: 202208151436