sorted()
The built-in sorted()
function returns a new sorted list from the elements of any iterable passed to it. It provides the flexibility to sort in ascending or descending order and allows customization of the sort order through a key function:
>>> sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
sorted()
Signature
sorted(iterable, *, key=None, reverse=False)
Arguments
Argument | Description | Default Value |
---|---|---|
iterable |
An iterable object like a list, tuple, or string that you want to sort. | Required argument |
key |
A one-argument function that extracts a comparison key from each element. | None |
reverse |
A Boolean that, if True , sorts the elements in descending order. |
False |
Return Value
- Returns a new sorted list of the elements in the iterable.
sorted()
Examples
With a list of numbers:
>>> sorted([4, 2, 7, 5, 1, 6, 3])
[1, 2, 3, 4, 5, 6, 7]
With a string:
>>> sorted("bdeac")
['a', 'b', 'c', 'd', 'e']
With a reverse argument:
>>> sorted([4, 2, 7, 5, 1, 6, 3], reverse=True)
[7, 6, 5, 4, 3, 2, 1]
sorted()
Common Use Cases
The most common use cases for the sorted()
function include:
- Sorting lists, tuples, or any iterable in ascending or descending order
- Customizing sort order using a key function
sorted()
Real-World Example
Imagine you have a list of student records, and you need to sort them first by grade and then by age. You can use the sorted()
function with a key
argument to achieve this:
>>> from operator import itemgetter
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(students, key=itemgetter(1, 2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
In this example, sorted()
helps by using itemgetter
from the operator
module to sort by the second element (grade) and then by the third element (age).
Related Resources
Tutorial
How to Use sorted() and .sort() in Python
In this step-by-step tutorial, you’ll learn how to sort in Python. You'll know how to sort various types of data in different data structures, customize the order, and work with two different ways of sorting in Python.
For additional information on related topics, take a look at the following resources:
- How to Sort Unicode Strings Alphabetically in Python (Tutorial)
- Strings and Character Data in Python (Tutorial)
- Lists vs Tuples in Python (Tutorial)
- Sorting Data With Python (Course)
- Strings and Character Data in Python (Course)
- Python Strings and Character Data (Quiz)
- Lists and Tuples in Python (Course)
- Lists vs Tuples in Python (Quiz)