Collections

Sorting

sorted returns a new ordered list and key functions choose the sort value.

sorted() accepts any iterable and returns a new list. The original collection is left untouched, which makes sorted() useful in expressions and pipelines.

Use key= to say what value should be compared for each item. This is the idiomatic way to sort records, tuples, dictionaries, and objects by a field.

Use reverse=True for descending order. Use list.sort() instead when you intentionally want to mutate an existing list in place.

sorted() returns a new list. Printing the original list afterward shows that the input order did not change.

Source

names = ["Guido", "Ada", "Grace"]
print(sorted(names))
print(names)

Output

['Ada', 'Grace', 'Guido']
['Guido', 'Ada', 'Grace']

A key function computes the value to compare. The lambda user: user["score"] expression is a small unnamed function that takes one record and returns its score (lambdas covers the form). Here the records are sorted by score, highest first, and the output shows the resulting order.

Source

users = [
    {"name": "Ada", "score": 10},
    {"name": "Guido", "score": 8},
    {"name": "Grace", "score": 10},
]
ranked = sorted(users, key=lambda user: user["score"], reverse=True)
print([user["name"] for user in ranked])

Output

['Ada', 'Grace', 'Guido']
Python's sort is stable: items with equal keys keep their original order, so chained sorts compose predictably.

list.sort() sorts the list in place. Use it when mutation is the point and no separate sorted copy is needed.

Source

users.sort(key=lambda user: user["name"])
print([user["name"] for user in users])

Output

['Ada', 'Grace', 'Guido']

Notes

See also

Run the complete example

Example code

Expected output

['Ada', 'Grace', 'Guido']
['Guido', 'Ada', 'Grace']
['Ada', 'Grace', 'Guido']
['Ada', 'Grace', 'Guido']

Execution time appears here after you run the example.