The list is the most flexible core data type in python, it represents a collection of ordered elements. Lists are mutable meaning that operations that actually modify the list are possible. One common operation on lists is modifying the list so that the elements are sorted based on a certain criteria.

The sort() method is used to sort the list elements in-place. This means that sorting is achieved by re-arranging  the elements of the same list rather than creating a new list object containing the elements in sorted order.

#a list of integers
mylist = [5, 0, 7, 3, 10, 4]

#sort the list
mylist.sort()
print(mylist)

The syntax of the sort() method is as shown below:

lst.sort(key = None, reverse = False)
key Optional. A function that will be used as a sorting criteria.
reverse Optional. A boolean value indicating whether the list elements should be sorted in reverse i.e from the largest to smallest. It defaults to False.

If the key argument is given, the the elements are sorted based on the return values of applying the function  to each element. If the key is not given, the elements are sorted based on their natural ordering.

Without a key function

mylist = [50, 20, 40, 10, 0, 30]

mylist.sort()
print(mylist)

In the above example, we do not provide a key function, the elements which are integers are therefore sorted based on their numerical value.

Sorting a list of strings

mylist = ['a', 'c', 'f', 'b', 'e', 'd']

mylist.sort()
print(mylist)

In the above example, the strings in the list are sorted based on their alphabetical values. 

sort() with a key function

The key argument allows us to define a custom sorting criteria by providing a function that will be applied to each of the list elements. The elements a re sorted based on the values returned by the key function rather than the natural ordering of the elements.

The key is typically a function that takes one argument, so that it will be called with each element in  the list.

sort integers by their absolute values

mylist = [-2, 0, 1, -3, -5, 4]

#sort the integers by absolute value using the abs function as key
mylist.sort(key = abs)
print(mylist)

In the above example, we have a list of positive and negative integers. In 'normal' sorting i.e without a key given, the the elements would have been sorted by their numerical values i.e from smallest to largest. By using the builtin abs()  function as key, which returns the absolute values of a number, we were able to  sort the list elements by their absolute values rather than by their numerical values.

sort strings by their lengths

#a list of strings
mylist = ['C++', 'Javascript', 'Python', 'Ruby', 'C']

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

In the above example, by using the builtin len() function as key, the strings are sorted by their length rather than by the alphabetical order of their characters.

sort tuples by their second value

# a list of tuples
mylist = [('C++', 3), ('Java', 1), ('Python', 2), ('C++', 4), ('Ruby', 0)]

mylist.sort(key = lambda x: x[1])
print(mylist)

In the above example, we have a list of tuples where each tuple contains a string and an integer values. We used a lambda function so that the tuples are sorted by the value of the integer element rather than looking at the tuple as a whole.

Sorting in reverse

By default, the sort() method sorts the elements in an ascending order. It, however, allows us to specify the reverse argument which is a boolean value indicating whether the elements should be sorted by descending order or not. The argument defaults to False, by setting it to True we effectively tell the sort() function to sort the elements in descending order.

sort integers in descending order

mylist = [10, 0, 30, 20, 50, 40]

mylist.sort(reverse = True)
print(mylist)

In the above example we sorted the integers  in a descending order based on their numerical values.

sort tuples in descending order

# a list of tuples
mylist = [('C++', 3), ('Java', 1), ('Python', 2), ('C++', 4), ('Ruby', 0)]

mylist.sort(key = lambda x: x[1], reverse = True)
print(mylist)

sort() vs sorted()

Python also contains a builtin function called sorted() which we can also use to sort the list elements just, it actually takes same arguments as the sort() method. However, unlike the sort() method, sorted() does not modify the list in place, instead it returns an entirely new list containing the elements of the original list in sorted order.

using sorted() function to sort a list

L = [0, 3, 1, 2, 5, 4]

#create a new sorted list
sorted_l = sorted(L)
print(sorted_l)

The sorted() function also works with any iterable not just lists.