A RetroSearch Logo

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

Search Query:

Showing content from https://realpython.com/ref/builtin-functions/sorted/ below:

Python’s Built-in Functions – Real Python

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() Signature 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 sorted() Examples

With a list of numbers:

With a string:

With a reverse argument:

sorted() Common Use Cases

The most common use cases for the sorted() function include:

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:

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).

For additional information on related topics, take a look at the following resources:


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