Python sorted()
Python sorted() builtin function is used to sort items in given iterable. We may specify a function based on which the sorting happens, and the order of sorting via parameters to sort() function.
In this tutorial, we will learn about the syntax of Python sorted() function, and learn how to use this function with the help of examples.
Syntax
The syntax of sorted() function is
sorted(iterable, *, key=None, reverse=False)
where
Parameter | Required/ Optional | Description |
---|---|---|
iterable | Required | An iterable object. |
* | Optional | More objects/items for sorting. |
key | Optional | A function. This function is used to to find a comparison value for each element in the iterable. This function must accept only one argument. Default value is None. |
reverse | Optional | The order in which sorting happens. Default value is False. |
Returns
The function returns a list.
Examples
1. Sort List of Integers
In this example, we take a list of integers and sort them using sorted() function.
Python Program
x = [14, 25, 1, 8, 4, 3]
result = sorted(x)
print(result)
Output
[1, 3, 4, 8, 14, 25]
2. Sort List of Strings based on Key Function
In this example, we take a list of strings and sort them based on the length of string using sorted() function. The key function would be len().
Python Program
x = ['banana', 'apple', 'cherry', 'orange']
result = sorted(x, key=len)
print(result)
Output
['apple', 'banana', 'cherry', 'orange']
‘banana’, ‘cherry’ and ‘orange’ are of same length. So, in terms of comparison, all these three elements are equal. sorted() preserves the relative order of similar elements.
3. Sort List of Integers in Descending Order
To sort in descending order using sorted() function, pass True for reverse
parameter.
Python Program
x = [14, 25, 1, 8, 4, 3]
result = sorted(x, reverse=True)
print(result)
Output
[25, 14, 8, 4, 3, 1]
Conclusion
In this Python Tutorial, we have learnt the syntax of Python sorted() builtin function, and also learned how to use this function, with the help of Python example programs.