Collections
Sorting
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. 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']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
sorted()makes a new list;list.sort()mutates an existing list.key=should return the value Python compares for each item.- Python's sort is stable, so equal keys keep their original relative order.
See also
Run the complete example
Expected output
['Ada', 'Grace', 'Guido']
['Guido', 'Ada', 'Grace']
['Ada', 'Grace', 'Guido']
['Ada', 'Grace', 'Guido']
Execution time appears here after you run the example.