Python sorted() Function
Example
Sort a tuple:
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.
Syntax
Parameter Values
| 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 |
More Examples
Example
Sort ascending:
x = sorted(a)
print(x)
Example
Sort descending:
x = sorted(a, reverse=True)
print(x)
Example
Sort using the key parameter.
To sort a list by length, we can use the built-in len function.
x = sorted(a, key=len)
print(x)
Example
Sort by a self made function for the key parameter.
Sort the list by the number closest to 10:
return abs(10-n)
a = (5, 3, 1, 11, 2, 12, 17)
x = sorted(a, key=myfunc)
print(x)