![]() |
VOOZH | about |
sorted() function in Python returns a new sorted list from the elements of any iterable, such as a list, tuple, set, or string. It does not modify the original iterable, unlike the sort() method for lists.
Let's start with a basic example of sorting a list of numbers in ascending order using the sorted() function.
[1, 2, 3, 4]
sorted(iterable, key=None, reverse=False)
Parameters:
Return Type: Returns a new sorted list containing all elements from the iterable according to the given criteria.
To sort an iterable in descending order, set the reverse argument to True.
[9, 6, 5, 5, 2, 1]
You can sort the characters of a string and return a list.
['h', 'n', 'o', 'p', 't', 'y']
Explanation: Each character of the string is treated as an element and sorted in ascending (alphabetical) order.
You can sort the elements of a tuple using sorted(), which returns a list.
[1, 2, 3, 4]
Explanation: Tuples are immutable, so sorted() returns a new sorted list, leaving the original tuple unchanged.
The key parameter is an optional argument that allows us to customize the sort order.
1. Sorting Strings by Length: You can sort a list of strings by their length using the key=len parameter in sorted().
['date', 'apple', 'banana', 'cherry']
Explanation: The key parameter is set to len, which sorts the words by their length in ascending order.
2. Sorting a List of Dictionaries: You can sort a list of dictionaries based on a specific key using sorted() with a lambda function.
[{'name': 'Eve', 'score': 78}, {'name': 'Harry', 'score': 85}, {'name': 'Leo', 'score': 91}]
Explanation: key=lambda x: x['score'] specifies that the sorting should be done using the 'score' value from each dictionary