Sort a List in Python
The sorted function returns a new list and can order complex values using a key function.
What is Sort a List?
The sorted function returns a new list and can order complex values using a key function.
Sort numbers and records in Python with sorted and a custom key.
When should you use it?
- Learn Python syntax through a practical example.
- Build a foundation for larger programming problems.
- Test an idea quickly without a local setup.
Example code
main.py
students = [
{"name": "Lin", "score": 88},
{"name": "Ada", "score": 95},
{"name": "Sam", "score": 91},
]
ranked = sorted(students, key=lambda student: student["score"], reverse=True)
print([student["name"] for student in ranked])
Expected output
['Ada', 'Sam', 'Lin']
How it works
The lambda extracts each student's score. Reverse order places the highest score first without modifying the original list.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.