Python Sorting · Exercises
Beginner

Python Sorting Exercises

4 exercises that build on the Python Sorting lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: Sorting puts items in order: sorted() returns a new sorted list and leaves the original alone, list.sort() rearranges the list in place and returns None, and the key= function decides what Python compares. By the end you can sort with sorted() and .sort(), reverse an order, sort by any rule with key=, order tuples and dictionaries, sort on several fields at once, and pick the best item with min() or max(). You will practise: Leaderboard without changing the scores; Predict the three orders; Fix the tie-break order; League standings.

0 / 4 completed

Python Sorting practice exercises

1. Leaderboard without changing the scores

Write code Easy

Complete the function leaderboard(scores). It must return a new list with the scores from highest to lowest, and it must not change the list it receives (the caller may still need the original order).

Your code
def leaderboard(scores):
    # return a NEW list, highest score first
    pass

results = [72, 95, 88, 61]
print(leaderboard(results))
print(results)

2. Predict the three orders

Predict the output Easy

Read the code and type exactly what it prints, line by line. Then press Check to run it and compare.

Read this code
words = ["banana", "apple", "Cherry", "Apple"]
print(sorted(words))
print(sorted(words, key=str.lower))
print(max(words, key=len))

3. Fix the tie-break order

Fix the bug Medium

rank_players(entries) should return the (name, score) pairs with the highest score first, and players on the same score in A to Z order. The sort puts tied players in Z to A order instead. Fix the function.

Your code
def rank_players(entries):
    # highest score first; ties in A-Z order
    return sorted(entries, key=lambda e: (e[1], e[0]), reverse=True)

print(rank_players([("Ben", 90), ("Asha", 90), ("Cara", 75), ("Dev", 82)]))

4. League standings

Write code Hard

Write standings(teams). teams is a list of dictionaries with the keys "name", "points", "goals_for" and "goals_against". Return a list of team names ordered by:

  1. most points first,
  2. then the best goal difference (goals_for - goals_against) first,
  3. then the name from A to Z.

Do not change the teams list you receive.

Your code
def standings(teams):
    # return the team names, best team first
    pass

table = [
    {"name": "Lions", "points": 10, "goals_for": 14, "goals_against": 9},
    {"name": "Tigers", "points": 10, "goals_for": 12, "goals_against": 6},
    {"name": "Bears", "points": 7, "goals_for": 8, "goals_against": 8},
    {"name": "Wolves", "points": 10, "goals_for": 11, "goals_against": 6},
]
print(standings(table))

Next lessonPython Sets

More Python Sorting examples · All Python exercises