Python lesson 28
Enumerate and Zip
Count while you loop, and walk two lists side by side.
The Counter You Do Not Have to Keep
enumerate gives you the position and the item together, so you stop writing counter = counter + 1 by hand. enumerate counts from 0. Writing start=1 when you call it says begin at 1 instead, and naming an argument like that works on any function that accepts it. Zip walks two lists at the same time, handing you one item from each.
for position, name in enumerate(names):
...
for position, name in enumerate(names, start=1):
... # 1st, 2nd, 3rd instead of 0, 1, 2
for question, answer in zip(questions, answers):
...
names = ["Nova", "Blaze", "Echo"]
for position, name in enumerate(names, start=1):
print(position, name)
Where Does Counting Start?
fruits = ["apple", "pear"]
for i, fruit in enumerate(fruits):
print(i, fruit)
Pair Them Up
A Real Leaderboard
Run it. Enumerate numbers the list for you.
scores = {"Blaze": 65, "Nova": 40, "Echo": 22}
ranked = ["Blaze", "Nova", "Echo"]
for place, name in enumerate(ranked, start=1):
print(place, name, scores[name])
Mark the Quiz
Compare each given answer with the correct one and count how many match.
correct = ["a", "c", "b", "d"]
given = ["a", "b", "b", "d"]
right = 0
for mine, theirs in zip(given, correct):
if mine == theirs:
right = right + 1
print("Score:", right, "out of", len(correct))
Number Every Line
Print a numbered shopping list, with the numbers starting at 1.
shopping = ["bread", "apples", "cheese"]
for number, item in enumerate(shopping, start=1):
print(str(number) + ". " + item)
What you can do on CodeIt
Run the example, change one part, and use the result to check your understanding before moving to the next lesson.