The sorted() function in Python is a built-in function used to sort the elements of an iterable object such as a list, tuple, string, or dictionary. It returns a new sorted list containing all the elements of the iterable.
Unlike the sort() method of lists, the sorted() function does not modify the original object. Instead, it creates and returns a new list with the elements arranged in sorted order.
By default, sorted() arranges elements in ascending order, but it can also sort in descending order or according to a custom sorting rule.
sorted(iterable, key=None, reverse=False)
Parameters
iterable The collection of elements to be sorted (list, tuple, string, etc.).
key (optional) A function that specifies the value used for sorting.
reverse (optional)
If True, the elements are sorted in descending order.
Default value is False, which means ascending order.
Return Value
numbers = [5, 2, 9, 1, 7]
result = sorted(numbers)
print(result)
Output
[1, 2, 5, 7, 9]
Explanation
numbers is sorted in ascending order.numbers = [5, 2, 9, 1, 7]
result = sorted(numbers, reverse=True)
print(result)
Output
[9, 7, 5, 2, 1]
Explanation
reverse=True sorts the elements in descending order.text = "python"
result = sorted(text)
print(result)
Output
['h', 'n', 'o', 'p', 't', 'y']
Explanation
numbers = (8, 3, 6, 1)
result = sorted(numbers)
print(result)
Output
[1, 3, 6, 8]
Explanation
key Parameterwords = ["apple", "banana", "kiwi", "cherry"]
result = sorted(words, key=len)
print(result)
Output
['kiwi', 'apple', 'banana', 'cherry']
Explanation
key=len tells Python to sort words based on their length rather than alphabetical order.data = {"b": 2, "a": 1, "c": 3}
result = sorted(data)
print(result)
Output
['a', 'b', 'c']
Explanation
sorted() sorts the keys.sorted() and list.sort()| Feature | sorted() | list.sort() |
|---|---|---|
| Works on | Any iterable | Only lists |
| Returns value | Returns a new sorted list | Returns None |
| Original data | Not modified | Modified |
Example:
numbers = [4, 2, 8]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
print(numbers)
Output:
[2, 4, 8]
[4, 2, 8]
sorted() is a built-in Python function used to sort iterable objects.key and reverse parameters.