Looping Over Lists
In this tutorial, we'll visit each item in a list.
A for loop repeats code once for each item in a collection.
names = ["Ada", "Grace", "Linus"]
for name in names:
print(name)
Output:
Ada
Grace
Linus
The Loop Variable
In this loop:
for name in names:
print(name)
name is the loop variable. Each time the loop runs, it points to the next item in the list.
First it is "Ada", then "Grace", then "Linus".
You can choose the variable name:
for student in names:
print(student)
Pick a name that describes one item.
Doing Work Inside the Loop
The indented lines run for every item:
scores = [8, 10, 7]
for score in scores:
doubled = score * 2
print(doubled)
Output:
16
20
14
Accumulating a Total
You can build up a total as you loop:
scores = [8, 10, 7]
total = 0
for score in scores:
total = total + score
print(total)
Output:
25
The total starts at zero and grows each time the loop runs.
Common Mistake
Do not use the list name when you mean the item:
for score in scores:
print(scores * 2) # wrong idea
Use the loop variable:
for score in scores:
print(score * 2)
Practice
Create a list of prices. Loop over the list and print each price with 20% tax added.