The sorted() function return a list of elements from an iterable object in a sorted manner. The sorting does not modify the original iterable object.
Example
#!/usr/bin/python3
print("sorted([23, 2, 3, 3, 4]): ", sorted([23, 2, 3, 3, 4]))
print("sorted([15, 2, 3, 1, 4]): ", sorted([15, 2, 3, 1, 4]))
print("sorted([52, 2, 3, 1, 334]): ", sorted([52, 2, 3, 1, 334], reverse = True))
Output:
sorted([23, 2, 3, 3, 4]): [2, 3, 3, 4, 23]
sorted([15, 2, 3, 1, 4]): [1, 2, 3, 4, 15]
sorted([52, 2, 3, 1, 334]): [334, 52, 3, 2, 1]
Syntax
sorted(iterable, key=None, reverse = False)
Parameters
Name | Description |
iterable | Iterable object including sequence (list, tuple, string) or collection (dictionary, set) |
key | Optional, A Function to execute which decides the order of sorting. Default is None |
reverse | Optional, A Boolean. Default is False and sorting ascending. If set true, sort descending |
Return Value
It returns a list of elements from an iterable object in sorted manner.