A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-sorted-function/ below:

Python sorted() Function - GeeksforGeeks

Python sorted() Function

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)
Syntax of sorted() function

sorted(iterable, key=None, reverse=False)

Parameters: Return Type: 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)

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: 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:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4