Beginner Python Exercises

Sort a List in Python with sorted() and key

Sort numbers, words or whole records by any field, ascending or descending, in one line.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • sorted() versus list.sort()
  • Sorting records with key=lambda
  • reverse=True for descending order
sorted(students, key=score, reverse=True)
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.

From test papers to code
students📄 The pile of papers
key=lambda student: student["score"]🔎 Look only at the score in the corner
reverse=True⬇️ Highest score on top
ranked🏆 A new, ordered pile; the old pile is untouched
The key picks what to compare; whole records move together.
In one sentence

sorted() 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

  1. sorted(students, ...) builds a new list and leaves students in its original order.
  2. key=lambda student: student["score"] tells sorted to compare the scores, not the whole dictionaries.
  3. reverse=True sorts from the highest score to the lowest.
  4. [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() or max() with the same key is faster.
  • You need the top few of a huge list: heapq.nlargest avoids sorting everything.

Example code

Run 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])
Get a Run button for this example

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.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in the Python compiler →

Common mistakes

Expecting sort() to return the list

list.sort() sorts in place and returns None.

Problem
ranked = students.sort(key=lambda s: s["score"])
print(ranked)  # None
Fix
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.

All challenges