How to Use the Python sorted() Function

09/17/2021
Contents
In this article, you will learn how to use the Python sorted() function.
Python sorted() Function
The sorted() function in Python is used to sort a list or any iterable in ascending order or in descending order.
Syntax
Here are the basic syntax and usage of the sorted() function:
sorted(iterable, key=None, reverse=False)
Parameters
iterable
: It can be any sequence like a list, tuple, set, or string.key
: It is an optional parameter that specifies a function to be called on each item in the iterable. The function takes one argument and returns a value to use for sorting purposes.reverse
: It is an optional parameter that specifies whether the iterable should be sorted in reverse order. It defaults to False (ascending order).
Example
Here are some examples of how to use the sorted() function:
Sorting a list of numbers in ascending order
numbers = [4, 2, 8, 1, 3, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
# Output: [1, 2, 3, 4, 6, 8]
Sorting a list of strings in ascending order
fruits = ['apple', 'banana', 'cherry', 'durian', 'elderberry']
sorted_fruits = sorted(fruits)
print(sorted_fruits)
# Output: ['apple', 'banana', 'cherry', 'durian', 'elderberry']
Sorting a list of strings in descending order
fruits = ['apple', 'banana', 'cherry', 'durian', 'elderberry']
sorted_fruits = sorted(fruits, reverse=True)
print(sorted_fruits)
# Output: ['elderberry', 'durian', 'cherry', 'banana', 'apple']
Sorting a list of tuples based on the second item
students = [('John', 95), ('Alice', 80), ('Bob', 75), ('Chris', 90)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
# Output: [('Bob', 75), ('Alice', 80), ('Chris', 90), ('John', 95)]
In the above example, the key parameter is used to specify a lambda function that takes a tuple and returns its second item. This means that the sorting is done based on the second item of each tuple.