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
- Sort by ageSort people by age, youngest first; people of the same age by name.Intermediate
- The podiumPrint the top three scores with their names, highest first.Intermediate
- Closest pairFind the smallest difference between any two numbers in a list.Intermediate
- Nearest pointsSort points by their distance from (0, 0), nearest first.Intermediate