Iteration: For Loops
Repeat a block of code once for each item in a sequence.
A for loop repeats a block of code once for each item in a sequence — the characters of a string, the values in a list. That is all a for loop ever does, and there is only one kind of for loop. This page shows you all of it.
The shape of every for loop
Every for loop you will ever write has the same shape: for item in sequence: followed by an indented body. The loop takes each item of the sequence in turn, puts it in the variable, and runs the body once for it. When the items run out, the loop ends.
names = ["Ava", "Ben", "Cara"]
for name in names:
print("Hello", name)Hello Ava Hello Ben Hello Cara
namesis a sequence — a list holding three values in order.for name in namesmeans: take each value in turn and call itname.- The indented body runs once per item — three items, three passes.
nameis an ordinary variable. You choose its name; the loop fills it.
Watch what name holds on each pass — the loop simply moves along the sequence:
| Pass | name holds | What prints |
|---|---|---|
| 1 | "Ava" | Hello Ava |
| 2 | "Ben" | Hello Ben |
| 3 | "Cara" | Hello Cara |
A string is a sequence too
A string is a sequence of characters, so the very same loop steps through it letter by letter.
word = "code"
for letter in word:
print(letter)c o d e
- Nothing about the loop changed — only the sequence after
in. - A 4-character string means 4 passes, with
letterholding one character each time.
range(). The loop always does exactly the same job: visit each item in turn and run the body once for it. If you can read for item in sequence:, you can read every for loop ever written.Doing something with each item
The body can do anything with the current item — like adding each value to a running total.
prices = [3, 5, 2]
total = 0
for price in prices:
total = total + price
print("Total:", total)Total: 10
totalstarts at 0 before the loop.- Each pass adds the current
pricetototal: first 3, then 5, then 2. - After the last item the loop ends, and
totalholds 10.
for price in prices, for letter in word, for name in names. It makes the body read like English.What you have learned
- A for loop runs its body once for each item in a sequence.
- Its shape is always the same:
for item in sequence:plus an indented body. - The loop variable is a normal variable that holds the current item on each pass.
- Strings and lists are both sequences — the loop treats them exactly the same way.
- There is only one for loop. What changes is the sequence you give it.