Open In App

Python sorted() Function

Last Updated : 08 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

a = [4, 1, 3, 2]

# Using sorted() to create a new sorted list without modifying the original list
b = sorted(a)
print(b)

Output
[1, 2, 3, 4]

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.

a = [5, 2, 9, 1, 3]

#Sorted() arranges the list in ascending order
b = sorted(a)
print(b)

Output
[1, 2, 3, 5, 9]

Sorting in descending order

To sort an iterable in descending order, set the reverse argument to True.

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)

Output
[9, 6, 5, 5, 2, 1]

Sorting using key parameter

The key parameter is an optional argument that allows us to customize the sort order.

Sorting Based on String Length:

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:

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:



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg