← Go Back

How to Sort a List or Tuple

The sorted() built-in function takes an iterable object and returns a list with the elements ordered from lowest to highest. The order criterion is defined by a key function that assigns a numerical value to each element.

>>> sorted([2, 3, 1])
[1, 2, 3]

The reverse parameter can be used to order results from highest to lowest.

>>> sorted([2, 3, 1], reverse=True)
[3, 2, 1]

The key argument must be a function that takes an element and returns a numerical value that will be considered to order that element with respect to the rest. For example, to sort a list of strings from smallest to largest based on the number of characters, use the built-in len() function:

>>> sorted(["Python", "Java", "C", "C++"], key=len)
['C', 'C++', 'Java', 'Python']

The same way, the following code puts the even numbers at the beginning of the list and the rest at the end.

>>> def is_even(n):
... return n % 2 == 0
...
>>> sorted(range(10), key=is_even, reverse=True)
[0, 2, 4, 6, 8, 1, 3, 5, 7, 9]

Because is_even(n) returns True (1) if n is even and False (0) otherwise.

lists tuples built-ins


🐍 You might also find interesting: