Start free

GCSE · 4 exercises

Python sorting

sorted() gives a new sorted list; list.sort() sorts the list itself. reverse=True sorts from largest to smallest.

key= says what to sort by: key=len sorts words by length, key=lambda p: p[1] sorts pairs by their second item.

people = [("Ann", 14), ("Bob", 12)]
for name, age in sorted(people, key=lambda p: p[1]):
    print(name, age)

Watch for: list.sort() gives back None: names = names.sort() loses the list. Use sorted() for a new one.

Exercises

  1. Sort by ageSort people by age, youngest first; people of the same age by name.Intermediate
  2. The podiumPrint the top three scores with their names, highest first.Intermediate
  3. Closest pairFind the smallest difference between any two numbers in a list.Intermediate
  4. Nearest pointsSort points by their distance from (0, 0), nearest first.Intermediate
Start with “Sort by age”