Python sorted() Function
Returns a sorted list, in ascending order or optionally in descending order.
Contrast this with the sort()
function, which does an in-place sort.
Syntax
Python
Copy Code
sorted(iterable, key = None, reverse = False)
Parameters
Parameter | Description |
---|---|
iterable |
Required. An iterable object containing items to be sorted. |
key |
Optional. A function that is used to compare items for the purpose of sorting. This function should return a value for a given item. This is typically used where items in the list are classes or complex objects rather than simple values, and so this function may return a representative value for this object that allows it to be easily sorted |
reverse |
Optional. A boolean value that specifies whether to sort the list in reverse order (True) or the 'usual' order (False) |
Example
Python
Copy Code
cars = ['Ford', 'Chevrolet', 'BMW', 'Mercedes'] sortedCars = sorted(cars) print('Original list: ', cars) print('Cars, in alphabetical order: ', sortedCars) cars = ['Ford', 'Chevrolet', 'BMW', 'Mercedes'] print('Original list: ', cars) reversedSortedCars = sorted(cars, reverse=True) print(f'Cars, in reverse alphabetical order: ', reversedSortedCars)
Output
Original list: ['Ford', 'Chevrolet', 'BMW', 'Mercedes'] Cars, in alphabetical order: ['BMW', 'Chevrolet', 'Ford', 'Mercedes'] Original list: ['Ford', 'Chevrolet', 'BMW', 'Mercedes'] Cars, in reverse alphabetical order: ['Mercedes', 'Ford', 'Chevrolet', 'BMW']
Notes
One can also specify how to sort the list. The following example sorts by the length of the strings.
Example
Python
Copy Code
def byLength(s): return len(s) cars = ['Ford', 'Chevrolet', 'BMW', 'Mercedes'] sortedCarsByNameLength = sorted(cars, key=byLength) print('Cars, sorted by the length of the name: ', sortedCarsByNameLength)
Output
Cars, sorted by the length of the name: ['BMW', 'Ford', 'Mercedes', 'Chevrolet']