Lesson 33 of 34 · Errors & Pythonic Tools
Python enumerate(), zip() and sorted() with key
Some of the most Pythonic code you'll ever write uses three humble built-ins. enumerate() and zip() let you loop without juggling indexes, and sorted() with a key function can put any data in exactly the order you want. Together they replace a surprising amount of clumsy, error-prone code.
enumerate(): counting while you loop
Beginners often write for i in range(len(items)): just to get a position number. enumerate() gives you the position and the item:
heroes = ["Ada", "Bo", "Cy"]
for index, hero in enumerate(heroes):
print(index, hero) # 0 Ada / 1 Bo / 2 Cy
for rank, hero in enumerate(heroes, start=1):
print(f"{rank}. {hero}") # 1. Ada / 2. Bo / 3. Cy
enumerate() works with any iterable — strings, files, generators — and start= sets the first number.
zip(): looping over several sequences at once
zip() pairs up items from two or more iterables, position by position:
names = ["Ada", "Bo", "Cy"]
scores = [98, 75, 88]
for name, score in zip(names, scores):
print(f"{name}: {score}")
roster = dict(zip(names, scores)) # {'Ada': 98, 'Bo': 75, 'Cy': 88}
By default zip() stops as soon as the shortest input runs out, silently dropping the rest. When the lengths must match, pass strict=True (Python 3.10+), and zip() raises a ValueError instead of hiding the problem:
list(zip([1, 2, 3], ["a", "b"])) # [(1, 'a'), (2, 'b')]
list(zip([1, 2, 3], ["a", "b"], strict=True)) # ValueError
sorted() with a key function
sorted() takes an optional key — a function that's called once per item to compute what to sort by:
words = ["banana", "Fig", "apple"]
print(sorted(words, key=len)) # ['Fig', 'apple', 'banana']
print(sorted(words, key=str.lower)) # ['apple', 'banana', 'Fig']
players = [("Bo", 75), ("Ada", 98), ("Cy", 88)]
print(sorted(players, key=lambda p: p[1], reverse=True))
# [('Ada', 98), ('Cy', 88), ('Bo', 75)]
Pass the function itself — key=len, not key=len(). The same key parameter works with min(), max() and list.sort():
print(max(players, key=lambda p: p[1])) # ('Ada', 98)
Sorting by several keys
Return a tuple from the key function: Python compares the first items, and only on a tie looks at the second, and so on. Negate numbers to sort them in descending order while the rest stays ascending:
heroes = [
{"name": "Bo", "level": 3},
{"name": "ada", "level": 5},
{"name": "Cy", "level": 3},
]
ranked = sorted(heroes, key=lambda h: (-h["level"], h["name"]))
print([h["name"] for h in ranked]) # ['ada', 'Bo', 'Cy']
Strings can't be negated: to sort text in descending order, use reverse=True or sort twice (Python's sort is stable). The operator.itemgetter and operator.attrgetter functions are handy shortcuts for common keys.
Bonus: any() and all()
any(iterable) is True if at least one item is truthy; all(iterable) if every item is. With a generator expression they read like English:
scores = [98, 75, 88]
print(any(s > 90 for s in scores)) # True
print(all(s >= 60 for s in scores)) # True
Common mistakes
range(len(items))loops when you need positions — useenumerate().- Silent truncation:
zip()drops leftovers from longer inputs unless you passstrict=True. - Expecting
sorted()to change the list: it returns a new list;list.sort()sorts in place and returnsNone. - Case-sensitive sorting: uppercase letters sort before lowercase ones (
"Zed" < "amy"). Usekey=str.lowerfor natural alphabetical order.
Assignment
Write three functions:
number_lines(lines)returns a new list where each line is prefixed with its line number, starting at 1:"1: <line>".pair_scores(names, scores)returns a dictionary mapping each name to the score at the same position. If the two lists have different lengths, raise aValueError(zip(..., strict=True)does this for you).sort_heroes(heroes)takes a list of dictionaries with"name"and"level"keys and returns the names, ordered by level from highest to lowest. Heroes with the same level are ordered alphabetically by name, ignoring case. The input list must not be reordered.
number_lines(["alpha", "beta"]) # ["1: alpha", "2: beta"]
pair_scores(["Ada", "Bo"], [98, 75]) # {"Ada": 98, "Bo": 75}
sort_heroes([{"name": "Bo", "level": 3}, {"name": "ada", "level": 5}])
# ["ada", "Bo"]Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .