The sorted() function sorts the elements of a given [[Python Iterators, iter and next|iterable]] in a specific order (ascending or descending) and returns it as a list.
Syntax
Parameter Values (input)
Parameter
Description
iterable
Iterator objects that will be joined together
reverse (Optional)
If True, the sorted list is reversed (or sorted in descending order). Defaults to False if not provided.
key (Optional)
A function that serves as a key for the sort comparison. Defaults to None.
Recommended Reading: [[Python Iterators, iter and next]]
Return Values
oss:
sorted() returns always a list independently of the input type
Example 1) Sort string, list, and tuple;
Example 2) Sort in descending order:
The sorted() function accepts a reverse parameter as an optional argument.
Setting reverse = True sorts the iterable in the descending order.
Key Parameter in Python sorted() function
If you want your own implementation for sorting, sorted() also accepts a key function as an optional parameter.
Based on the returned value of the key function, you can sort the given iterable.
Example 1:
Here, len() is Python’s in-built function to count the length of an object.
The list is sorted based on the length of the element, from the lowest count to highest.