Python sorted() Function
Example
Sort Tuples:
a = ("b", "g", "a", "d", "f", "c", "h", "e") x = sorted(a) print(x)
Definition and Usage
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.
Note:You cannot sort a list that contains both string values and numeric values at the same time.
Syntax
sorted(iterable, key=key, reverse=reverse)
Parameter Value
Parameter | Description |
---|---|
iterable | Required. The sequence to be sorted, such as a list, dictionary, tuple, etc. |
key | Optional. Execute a function to determine the order. The default is None. |
reverse | Optional. Boolean value. False will be sorted in ascending order, True will be sorted in descending order. The default is False. |
More Examples
Example
Numeric Sorting:
a = (2, 35, 17) x = sorted(a) print(x)
Example
Ascending Order Sorting:
a = ("h", "b", "a", "c", "f", "d", "g", "e") x = sorted(a) print(x)
Example
Descending Order Sorting:
a = ("h", "b", "a", "c", "f", "d", "g", "e") x = sorted(a, reverse=True) print(x)