Python sorted() Function (original) (raw)
Last Updated : 08 Mar, 2025
sorted() function returns a new sorted list from the elements of any iterable like (e.g., list, tuples, strings ). It creates and returns a new sorted list and leaves the original iterable unchanged.
Let’s start with a basic example of sorting a list of numbers using the sorted() function.
Python `
a = [4, 1, 3, 2]
Using sorted() to create a new sorted list without modifying the original list
b = sorted(a) print(b)
`
Table of Content
- Syntax of sorted() function
- Sorting in ascending order
- Sorting in descending order
- Sorting using key parameter
Syntax of sorted() function
sorted(iterable, key=None, reverse=False)
**Parameters:
- **iterable: The sequence to be sorted. This can be a list, tuple, set, string, or any other iterable.
- **key (Optional): A function to execute for deciding the order of elements. By default it is **None
- **reverse (Optional): If **True, sorts in descending order. Defaults value is **False (ascending order)
Return Type:
- Returns a new list containing all elements from the given iterable, sorted according to the provided criteria.
Sorting in ascending order
When no additional parameters are provided then It arranges the element in increasing order.
Python `
a = [5, 2, 9, 1, 3]
#Sorted() arranges the list in ascending order b = sorted(a) print(b)
`
Sorting in descending order
To sort an iterable in descending order, set the **reverse argument to **True.
Python `
a = [5, 2, 9, 1, 5, 6]
"reverse= True" helps sorted() to arrange the element
#from largest to smallest elements res = sorted(a, reverse=True) print(res)
`
Sorting using _key parameter
The **key parameter is an optional argument that allows us to customize the sort order.
Sorting Based on String Length:
Python `
a = ["apple", "banana", "cherry", "date"] res = sorted(a, key=len) print(res)
`
Output
['date', 'apple', 'banana', 'cherry']
**Explanation: The **key parameter is set to **len, which sorts the words by their length in ascending order.
Sorting a List of Dictionaries:
Python `
a = [ {"name": "Alice", "score": 85}, {"name": "Bob", "score": 91}, {"name": "Eve", "score": 78} ]
Use sorted() to sort the list 'a' based on the 'score' key
sorted() returns a new list with dictionaries sorted by the 'score'
b = sorted(a, key=lambda x: x['score']) print(b)
`
Output
[{'name': 'Eve', 'score': 78}, {'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 91}]
**Explanation: key=lambda x: x[‘score’] specifies that the sorting should be done using the ‘score’ value from each dictionary
**Related Articles: