The for Loop in Python
A for loop runs a block of code once for each item in a sequence. That sequence can be a list, a string or a range of numbers, and Python sets the loop variable to the next item on every pass, so you never write the counting yourself. range() supplies the numbers when you want to repeat something a set number of times.
Key facts
for item in sequence:runs the indented block once per item, in order. The header ends with a colon.range(5)gives 0, 1, 2, 3 and 4. The stop value is never included.range(1, 11)counts from 1 to 10, andrange(10, 0, -1)counts down from 10 to 1.enumerate()gives each item together with its position, starting at 0.- The loop variable keeps its last value after the loop ends.
What is a for loop in Python?
A for loop runs a block of code once for each item in a sequence. The header names a loop variable and the thing to loop over, ends with a colon, and the indented block under it runs one time per item, in order. Anything Python can hand out one item at a time is called an iterable, and lists, strings and ranges all qualify.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
print("Done")apple banana cherry Done
Each pass through the block is one iteration. On the first pass, fruit is "apple", on the second it is "banana", and when the list runs out, Python moves to the first line after the block, which prints Done.
How do I loop a set number of times with range()?
Loop over range(), which produces a sequence of whole numbers. range(5) starts at 0 and stops before 5, so the block runs five times with 0, 1, 2, 3 and 4.
for i in range(5):
print(i)
print(range(5))
print(list(range(5)))0 1 2 3 4 range(0, 5) [0, 1, 2, 3, 4]
range(5) is not a list. Printing it shows range(0, 5), because a range produces each number as the loop asks for it instead of storing them all. Pass the range to list() when you want to see every value at once.
| Call | Meaning | Example | Values |
|---|---|---|---|
range(stop) | From 0 up to, but not including, stop | range(4) | 0, 1, 2, 3 |
range(start, stop) | From start up to, but not including, stop | range(2, 6) | 2, 3, 4, 5 |
range(start, stop, step) | From start in steps of step, stopping before stop | range(0, 10, 3) | 0, 3, 6, 9 |
How do I count from 1 to 10 in a for loop?
Give range() a start value. range(1, 11) counts from 1 to 10, because the stop value 11 is left out. A third value sets the step, and a negative step counts down.
for n in range(1, 6):
print(n)
print(list(range(1, 11)))
print(list(range(0, 11, 2)))
print(list(range(10, 0, -2)))1 2 3 4 5 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [0, 2, 4, 6, 8, 10] [10, 8, 6, 4, 2]
The three printed lists show what each range holds. range(10, 0, -2) starts at 10 and steps down by 2, stopping before 0. To walk an existing list backward, loop over reversed() instead of building a range.
for n in range(3, 0, -1):
print(n)
print("Liftoff!")
for fruit in reversed(["apple", "banana", "cherry"]):
print(fruit)3 2 1 Liftoff! cherry banana apple
Can I loop over a string or a list?
Yes. A string hands out one character per pass and a list hands out one item, so the same loop shape works for both. A running total is the usual reason to loop over a list of numbers.
for letter in "hey":
print(letter)
prices = [4.5, 12, 3.25]
total = 0
for price in prices:
total = total + price
print(total)h e y 19.75
total starts at 0 outside the loop, and each pass adds the current price to it. The shorthand total += price does the same job as total = total + price. Lists get their own lesson later in the course, and the built-in sum(prices) adds them up in one call.
How do I get the index in a for loop?
Loop over enumerate(items), which gives each item together with its position, also called its index. Write two names before in, one for the position and one for the item. The position starts at 0 unless you pass start=1.
fruits = ["apple", "banana", "cherry"]
for position, fruit in enumerate(fruits, start=1):
print(position, fruit)
for i in range(len(fruits)):
print(i, fruits[i])1 apple 2 banana 3 cherry 0 apple 1 banana 2 cherry
The second loop gets the position the long way, counting from 0, with range(len(fruits)) and the same square brackets you used on strings. It works, and it is the form other languages train you to write, but it is longer and the index is one more thing to get wrong.
| Loop header | What you get | Use it when |
|---|---|---|
for i, item in enumerate(items): | The position and the item together, counting from 0 or from start= | You need the position, with or without the item |
for i in range(len(items)): | Only the position, and you write items[i] yourself | You need the same position in two lists at once |
What happens to the loop variable after the loop?
The loop variable keeps its last value after the loop ends. Changing the loop variable inside the block doesn't change what the next pass receives, because Python takes the next item from the sequence, not from the variable. When you never use the variable, name it _ to say so.
for i in range(3):
i = i * 10
print(i)
print(i)
for _ in range(2):
print("Hello")0 10 20 20 Hello Hello
Inside the loop, i was multiplied by 10, and the next pass still received 1 and then 2 from the range. After the loop, i holds 20, its last value. If the range had been empty, the loop would have run zero times and i would never have been created.
Common mistakes with for loops in Python
Three of these four mistakes with for loops stop the program with a message that names the line. The fourth runs fine and prints one number too few.
- TypeError: 'int' object is not iterable. The loop was given a number, as in
for i in 5:orfor i in len(items):. A number is nothing to loop over. Userange(5)orrange(len(items)), or loop over the items themselves. - IndentationError: expected an indented block after 'for' statement on line 1. The line under the header isn't indented. Add four spaces.
- SyntaxError: expected ':'. The colon at the end of the header is missing.
- Stopping one short.
range(1, 10)ends at 9 because the stop value is never included. To count to 10, writerange(1, 11).
Run the two broken programs to see the messages, then fix them in the editor.
for i in 5:
print(i)Traceback (most recent call last):
File "main.py", line 1, in <module>
for i in 5:
^
TypeError: 'int' object is not iterablefor i in range(3):
print(i) File "main.py", line 2
print(i)
^^^^^
IndentationError: expected an indented block after 'for' statement on line 1Exercise
Write one line inside the loop that adds each price to total, so the program prints the three prices on their own lines and then Total: 19.75. The starter prints the prices but leaves the total at 0.
prices = [4.5, 12, 3.25]
total = 0
for price in prices:
print(price)
print("Total:", total)
4.5 12 3.25 Total: 19.75
Show the solution
prices = [4.5, 12, 3.25]
total = 0
for price in prices:
print(price)
total = total + price
print("Total:", total)
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this program print?
for i in range(3): print(i)range(3) starts at 0 and stops before 3, so the loop runs three times with 0, 1 and 2. Nothing prints the number 3 itself.
-
2What does this program print?
for n in range(1, 4): print(n)The stop value 4 is left out, so range(1, 4) gives 1, 2 and 3. Reading the two arguments as "from 1 to 4" is the mistake to avoid.
-
3Which loop header runs ten times without an error?
A for loop needs something to loop over, and range(10) supplies the numbers 0 to 9. A bare number is not iterable, so for i in 10: fails with a TypeError, and the semicolon form belongs to C and JavaScript.
-
4What does this program print?
word = "hi" for ch in word: print(ch)A string hands out one character per pass, so the loop prints h and then i on separate lines. Printing the whole word needs a print outside the loop.
-
5What does this program print?
fruits = ["a", "b"] for i, f in enumerate(fruits, start=1): print(i, f)enumerate() gives the position with each item, and start=1 makes the first position 1 instead of 0. Without start=1 the output would begin with 0 a.