Learn

Short lessons with real code you can edit and run on the page.

The for Loop in Python

Lesson 13 Python 3.14 Runs in your browser Updated
In short

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, and range(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.

Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
print("Done")
Output
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.

Python
for i in range(5):
    print(i)
print(range(5))
print(list(range(5)))
Output
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.

Python range() arguments
CallMeaningExampleValues
range(stop)From 0 up to, but not including, stoprange(4)0, 1, 2, 3
range(start, stop)From start up to, but not including, stoprange(2, 6)2, 3, 4, 5
range(start, stop, step)From start in steps of step, stopping before stoprange(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.

Python
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)))
Output
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.

Python
for n in range(3, 0, -1):
    print(n)
print("Liftoff!")
for fruit in reversed(["apple", "banana", "cherry"]):
    print(fruit)
Output
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.

Python
for letter in "hey":
    print(letter)
prices = [4.5, 12, 3.25]
total = 0
for price in prices:
    total = total + price
print(total)
Output
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.

Python
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])
Output
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.

enumerate() compared with range(len()) in a Python for loop
Loop headerWhat you getUse 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] yourselfYou 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.

Python
for i in range(3):
    i = i * 10
    print(i)
print(i)
for _ in range(2):
    print("Hello")
Output
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: or for i in len(items):. A number is nothing to loop over. Use range(5) or range(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, write range(1, 11).

Run the two broken programs to see the messages, then fix them in the editor.

Python
for i in 5:
    print(i)
Output
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    for i in 5:
             ^
TypeError: 'int' object is not iterable
Python
for i in range(3):
print(i)
Output
  File "main.py", line 2
    print(i)
    ^^^^^
IndentationError: expected an indented block after 'for' statement on line 1

Exercise

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.

Python
prices = [4.5, 12, 3.25]
total = 0
for price in prices:
    print(price)
print("Total:", total)
Output
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.

  1. 1What does this program print?

    for i in range(3):
        print(i)
  2. 2What does this program print?

    for n in range(1, 4):
        print(n)
  3. 3Which loop header runs ten times without an error?

  4. 4What does this program print?

    word = "hi"
    for ch in word:
        print(ch)
  5. 5What does this program print?

    fruits = ["a", "b"]
    for i, f in enumerate(fruits, start=1):
        print(i, f)

Frequently asked questions

What does a for loop do in Python?
A for loop runs a block of code once for each item in a sequence. The sequence can be a list, a string or a range of numbers, and Python moves the loop variable to the next item on every pass until the sequence runs out.
How do I loop from 1 to 10 in Python?
Loop over range(1, 11). The first value is where the count starts and the second is the first number left out, so range(1, 11) gives 1 to 10.
What does the underscore mean in a Python for loop?
The underscore _ is an ordinary variable name that signals the value is not used. for _ in range(3) repeats a block three times without pretending the number matters.
Is range() a function or a class?
range is a built-in type, so range(5) builds a range object the same way int("5") builds an int. Calling it looks like calling a function, which is why it gets called both a function and a class.
How do I loop with an index in Python?
Loop over enumerate(items), which pairs each item with its position, counting from 0. Pass start=1 to count from 1, or loop over range(len(items)) and index the list yourself.
How do I repeat something 3 times in Python?
Loop over range(3). The block under for _ in range(3) runs three times, and the underscore says the count itself is not used.