Python sorted() Function (original) (raw)
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.
Python `
a = [4, 1, 3, 2] b = sorted(a) print(b)
`
Syntax
sorted(iterable, key=None, reverse=False)
**Parameters:
- **iterable: The sequence to be sorted (list, tuple, set, string, etc.)
- **key (Optional): A function to customize the sort order. Default is None.
- **reverse (Optional): If True, sorts in descending order. Default is False.
**Return Type: Returns a new sorted list containing all elements from the iterable according to the given criteria.
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] res = sorted(a, reverse=True) print(res)
`
Sorting a String
You can sort the characters of a string and return a list.
Python `
s = "python" res = sorted(s) print(res)
`
Output
['h', 'n', 'o', 'p', 't', 'y']
**Explanation: Each character of the string is treated as an element and sorted in ascending (alphabetical) order.
Sorting a Tuple
You can sort the elements of a tuple using sorted(), which returns a list.
Python `
t = (3, 1, 4, 2) res = sorted(t) print(res)
`
**Explanation: Tuples are immutable, so sorted() returns a new sorted list, leaving the original tuple unchanged.
Sorting using key Parameter
The keyparameter 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().
Python `
a = ["apple", "banana", "cherry", "date"] res = sorted(a, key=len) print(res)
`
Output
['date', 'apple', 'banana', 'cherry']
**Explanation: The keyparameter 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.
Python `
a = [ {"name": "Harry", "score": 85}, {"name": "Leo", "score": 91}, {"name": "Eve", "score": 78} ]
b = sorted(a, key=lambda x: x['score']) print(b)
`