Python sorted()

The sorted() function sorts the elements of a given iterable in a specific order (ascending or descending) and returns it as a list.

Example


Syntax of sorted()

The syntax of the sorted() function is:

sorted(iterable, key=None, reverse=False)

sorted() Parameters

sorted() can take a maximum of three parameters:

  • iterable - A sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any other iterator.
  • reverse (Optional) - If True, the sorted list is reversed (or sorted in descending order). Defaults to False if not provided.
  • key (Optional) - A function that serves as a key for the sort comparison. Defaults to None.

sorted() Return Value

The sorted() function returns a sorted list.


Example 1: Sort string, list, and tuple

Output

['a', 'e', 'i', 'o', 'u']
['P', 'h', 'n', 'o', 't', 'y']
['a', 'e', 'i', 'o', 'u']

Notice that in all cases that a sorted list is returned.

Note: A list also has the sort() method which performs the same way as sorted(). The only difference is that the sort() method doesn't return any value and changes the original list.


Example 2: Sort in descending order

The sorted() function accepts a reverse parameter as an optional argument.

Setting reverse = True sorts the iterable in the descending order.

Output

['u', 'o', 'i', 'e', 'a']
['u', 'o', 'i', 'e', 'a']
['u', 'o', 'i', 'e', 'a']

key Parameter in Python sorted() function

If you want your own implementation for sorting, sorted() also accepts a key function as an optional parameter.

Based on the returned value of the key function, you can sort the given iterable.

sorted(iterable, key=len)

Here, len() is Python's in-built function to count the length of an object.

The list is sorted based on the length of the element, from the lowest count to highest.


Example 3: Sort the list using sorted() having a key function

Output

Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]

Example 4: Sorting with multiple keys

Let us suppose that we have the following list:

# Nested list of student's info in a Science Olympiad
# List elements: (Student's Name, Marks out of 100, Age)

participant_list = [
    ('Alison', 50, 18),
    ('Terence', 75, 12),
    ('David', 75, 20),
    ('Jimmy', 90, 22),
    ('John', 45, 12)
]

We want to sort the list in such a way that the student with the highest marks is in the beginning. In case the students have equal marks, they must be sorted so that the younger participant comes first.

We can achieve this type of sorting with multiple keys by returning tuple instead of a number.

Two tuples can be compared by comparing their elements starting from first. If there is a tie (elements are equal), the second element is compared, and so on.

>>> (1,3) > (1, 4)
False
>>> (1, 4) < (2,2)
True
>>> (1, 4, 1) < (2, 1)
True

Let's use this logic to build our sorting logic.

Output

[('Jimmy', 90, 22), ('Terence', 75, 12), ('David', 75, 20), ('Alison', 50, 18), ('John', 45, 12)]

Since the sorting logic function is small and fits in one line, lambda function is used inside key rather than passing a separate function name.

The above program can be written using the lambda function in the following way:

Output

[('Jimmy', 90, 22), ('Terence', 75, 12), ('David', 75, 20), ('Alison', 50, 18), ('John', 45, 12)]

To learn more about lambda functions, visit Python Lambda Functions.