Sort a List in Python with sorted() and key
Sort numbers, words or whole records by any field, ascending or descending, in one line.
- sorted() versus list.sort()
- Sorting records with key=lambda
- reverse=True for descending order
1stAda (95)2ndSam (91)3rdLin (88)The key decides the order
The problem
Leaderboards, product lists and reports all need sorting, and real data is rarely a plain list of numbers. Students have names and scores, products have prices and ratings. You need to say which field decides the order.
Think of it like this
Sorting records with a key is like a teacher arranging test papers by the score written in the corner. The teacher looks only at the score to decide the order, but each whole paper moves to its place, name and all.
students📄 The pile of paperskey=lambda student: student["score"]🔎 Look only at the score in the cornerreverse=True⬇️ Highest score on topranked🏆 A new, ordered pile; the old pile is untouchedsorted() returns a new list with the items in order; the key function decides what is compared and reverse=True puts the largest first.
Key points
sorted(students, ...)builds a new list and leavesstudentsin its original order.key=lambda student: student["score"]tellssortedto compare the scores, not the whole dictionaries.reverse=Truesorts from the highest score to the lowest.[student["name"] for student in ranked]keeps only the names to print the ranking.
When should you use it?
- Leaderboards, top-10 lists and rankings.
- Sorting records by a field such as price, date or name.
- Preparing data for display or for a binary search.
When not to use it
- You only need the smallest or largest item:
min()ormax()with the same key is faster. - You need the top few of a huge list:
heapq.nlargestavoids sorting everything.
Example code
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])
Result of running the code
['Ada', 'Sam', 'Lin']
Code explanation
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.
Common mistakes
Expecting sort() to return the list
list.sort() sorts in place and returns None.
ranked = students.sort(key=lambda s: s["score"])
print(ranked) # None
ranked = sorted(students, key=lambda s: s["score"])
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Median of a List Find the middle value of a list after sorting. Easy
- Second Largest Value Find the second largest distinct value. Easy