enumerate, zip, and sorted(key=...)
Three builtins replace a lot of manual index juggling.
enumerate
When you need both the index and the value, do not reach for range(len(...)). Use enumerate:
names = ["Ada", "Linus", "Grace"]
for i, name in enumerate(names):
print(i, name)
# 0 Ada / 1 Linus / 2 Grace
# start counting from 1
for rank, name in enumerate(names, start=1):
print(rank, name)zip
zip walks two (or more) sequences in lockstep, pairing items by position:
names = ["Ada", "Linus"]
ages = [36, 54]
for name, age in zip(names, ages):
print(f"{name} is {age}")
pairs = dict(zip(names, ages)) # {'Ada': 36, 'Linus': 54}sorted with a key
sorted returns a new sorted list. The key argument takes a function that maps each item to the value you want to sort by. A lambda is a tiny inline function, perfect for this:
people = [("Ada", 36), ("Grace", 85), ("Linus", 54)]
by_age = sorted(people, key=lambda p: p[1])
oldest_first = sorted(people, key=lambda p: p[1], reverse=True)The key runs once per item; Python sorts by the values it returns.
Write rank_scores(scores) that takes a list of (name, score) tuples and returns a new list of "1. Name (score)" strings, sorted highest score first, numbered from 1. For input [("Ada", 30), ("Bo", 90)] it returns ["1. Bo (90)", "2. Ada (30)"]. Use sorted with a key and enumerate with start=1.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.