Data Structures · Lists · lesson 4 of 10
Iterating over lists
about 12 minutes · free · runs in your browser
Step 1 of 2
Walking a list properly
The plain for loop hands you each value directly:
for name in names:
print(name)
When you need the position as well, enumerate() gives you both:
for index, name in enumerate(names):
print(index, name)
That is much better than for i in range(len(names)): followed by names[i] — which
works, but reads like a translation from another language.
To walk two lists together, zip() pairs them up and stops at the shorter one:
for name, score in zip(names, scores):
print(name, score)
Your turn: write numbered(items) returning a list of strings like
"1. apple", numbering from one.
You start from this, and edit it in the browser:
def numbered(items):
# Return ["1. apple", "2. pear", ...]
pass
Step 2 of 2
Pairing lists with zip
zip() is the clean answer whenever two lists line up index for index.
Your turn: write totals(names, scores) returning a list of strings like
"Ada: 90". Stop at the shorter list — zip does that for you.
You start from this, and edit it in the browser:
def totals(names, scores):
# Return ["Ada: 90", ...]
pass