[ Web Proxy ]
URL:
Viewing: https://www.pythonbyexample.dev/examples/sorting [Back]  [Original]

Sorting Python By Example Skip to main content Python By ExampleJourneysAbout
All examplesPython docs reference

Collections

Sorting

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

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']
INPUTSTABLE SORT BY KEY2 Ada1 Bo1 Bo1 Cy2 Eve2 Ada1 Cy2 EvePython'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

Comprehension PatternsCollections Module

Run the complete 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.

adewale/pythonbyexample Python 3.13 docs Privacy
Web Proxy Viewer  |  New URL  |  Original Page