The sorted() built-in function constructs a new list containing all items from the provided iterable in ascending order. Unlike methods designed specifically for list objects, this utility supports strings, tuples, sets, dictionaries, and generator expressions without altering the original sequence.
Distinction from list.sort()
The primary difference lies in mutability and return values. The list.sort() method modifies the list object directly in-place and returns None. In contrast, sorted() always generates a fresh list, leaving the source data intact. This immutability makes sorted() safer when preserving the original input state is critical.
Function Signature
sorted(iterable, *, key=None, reverse=False)
- iterable: Any object that can be iterated over (e.g., tuple, string, dictionary).
- key: An optional callable used to extract a specific comparison key from each element.
- reverse: A boolean flag determining sort direction. Set to
Truefor descending order;Falseis the default for ascending.
Implementation Examples
Sorting standard numeric sequences:
numeric_sequence = (42, 15, 9)
sorted_list = sorted(numeric_sequence)
print(sorted_list)
Output: [9, 15, 42]
Applying descending order logic:
values = [100, 50, 20]
descending_result = sorted(values, reverse=True)
print(descending_result)
Output: [100, 50, 20]