zip, enumerate & ranking
Pair and number things
Lesson 7 of 20 · 9 min · Module 2: Work with data efficiently
Data often arrives as parallel lists: one of names, one of scores. zip pairs them up and enumerate numbers them, so you never juggle indexes by hand.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Pair parallel lists with zip
- Number items with enumerate
- Sort stably by one field
The idea
zip(a, b) yields pairs (a[0], b[0]), (a[1], b[1])… and stops at the shorter list; zip(a, b, strict=True) raises ValueError when lengths differ. enumerate(items, start=1) yields (1, first), (2, second)…
names = ["Ana", "Bob"]
scores = [91, 78]
for rank, (name, score) in enumerate(zip(names, scores), start=1):
print(rank, name, score)
01zip stops early by default
zip(["a", "b", "c"], [1, 2]) quietly drops "c". With strict=True (Python 3.10+), a length mismatch raises ValueError, which turns a hidden data bug into a clear error.
print(list(zip(["a", "b"], [1, 2])))[('a', 1), ('b', 2)]02enumerate replaces range(len(...))
for i, item in enumerate(items, start=1) is clearer and less error-prone than indexing with range(len(items)).
03Stable sorting
Python’s sort never reorders items whose keys are equal, even with reverse=True. That gives fair, predictable tie handling for free.
Your turn
leaderboard(names, scores) that returns lines like "1. Mia (95)", highest score first; equal scores keep the order of the input. Raise ValueError if the lists have different lengths.What the checks look for
- Ranks names by score
- Keeps input order for equal scores
- Handles empty lists
- Rejects lists of different lengths
Take this with you
zip pairs, enumerate numbers, and a key decides how things are ordered.
Go a little further
Give equal scores the same rank (1, 2, 2, 4), as in sports tables.