Definition
The sorted() function returns a sorted list of the specified iterable object.
You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.
Syntax
sorted(iterable, key=key, reverse=reverse)
Parameters
Parameter | Description |
---|---|
iterable | Required. The sequence to sort, list, dictionary, tuple etc. |
key | Optional. A Function to execute to decide the order. Default is None |
reverse | Optional. A Boolean. False will sort ascending, True will sort descending. Default is False |
Examples
myNumbers = (4, 13, 12)
sortedNum = sorted(myNumbers)
print(sortedNum)
# ascending sort
myChars = ("h", "b", "a", "c", "f", "d", "e", "g")
ascChars = sorted(myChars)
print(ascChars)
# descending sort
descChars = sorted(myChars, reverse=True)
print(descChars)