PythonBuilt-in functions
sorted()
Returns a new, sorted list built from the items of any collection.
- Returns
- A new, sorted list.
Example
#Python
scores = [72, 95, 64, 88]
print(sorted(scores))
print(sorted(scores, reverse=True))
print(sorted(["Python", "CSS", "HTML"], key=len))
print(scores)Resultsaved result, you can check it
[64, 72, 88, 95]
[95, 88, 72, 64]
['CSS', 'HTML', 'Python']
[72, 95, 64, 88]
Definition and usage
#The sorted() function creates a new list with sorted items. The original collection stays unchanged, so it also works on tuples, sets, and strings.
The key parameter takes a function whose result decides the order, for example key=len sorts by length, and key=lambda s: s["points"] sorts by a dictionary field. The reverse=True parameter reverses the order.
Sorting in Python is stable: items with equal keys keep their relative order. That lets you sort by several criteria, by sorting first by the less important one.
Syntax
#Syntax
sorted(iterable, key=None, reverse=False)Parameters
#iterable
a collection
The items to sort.key
function, optional
A function that computes the sort key.reverse
bool, default False
Descending order whenTrue.
More examples
#Python
students = [
{"name": "Jack", "points": 90},
{"name": "Emma", "points": 120},
{"name": "Mia", "points": 90},
]
ranking = sorted(students, key=lambda s: (-s["points"], s["name"]))
print([s["name"] for s in ranking])Resultsaved result, you can check it
['Emma', 'Jack', 'Mia']
Good practices
#- To sort by several criteria, return a tuple from
key, e.g.(-points, name). - If you want to sort a list in place, without creating a new one, use the
list.sort()method.
Related entries
#- sort() vs sorted()list.sort() sorts the list in place and returns None, while sorted() returns a new, sorted list from any collection and leaves the original untouched.
- list.sort()Sorts a list in place.
- reversed()Returns an iterator that walks through a sequence from the end.
- lambdaA short anonymous function written as a single expression.
- min()Returns the smallest item in a collection, or the smallest of several arguments.
- ord()Returns the Unicode code point of a single character, e.g. ord("A") is 65. The opposite of chr().
Spotted a mistake or missing an example? Write to us.