Skip to contentSkip to navigation

Module 02 · Lesson 04

Definite Iteration & for Loops

Repeat work for every item with for loops: walk through strings and lists, count with range(), build running totals, and get positions with enumerate().

  • About 8 minutes
  • Beginner friendly
  • 12-question quiz at the end

What you will learn

  • Loop over items
  • Count with range()
  • Draw with loops
  • Watch a loop go round

Repeat for every item

A `for` loop runs the same lines once for each item, so you write them only once.

  • for item in things

    for fruit in basket: takes each item in turn and gives it the name fruit.

  • range()

    range(5) counts 0, 1, 2, 3, 4. It stops just before the number you give it.

  • The block

    The indented lines under the colon run once per item. The first line that is not indented runs after the loop.

  • Anything in a row

    Loop over a list, the letters of a word or a range() of numbers.

Loops run the world

Whenever a computer does the same thing many times, a loop is doing the work.

  • PlaylistsFor every song in the playlist: play it, then move to the next one.
  • GamesFor every enemy on screen: move it one step, sixty times a second.
  • Photo appsFor every photo in an album: make a small preview picture.
  • Class registersFor every name on the list: call it out and tick who is here.

The first line of a loop

Every `for` loop starts with a line like this. Tap each part to see its job.

Part 1 of 7

Tap any part of the code below, or press Next.1 of 7 explored

keyword:for starts a loop that will visit items one at a time.

Loops draw shapes

A turtle pen walks forward and turns. Put those two moves in a `for` loop and they repeat. Pick a shape or slide the numbers, and watch the loop under the drawing change.

Shape 1 of 5Square

Real Python opens the turtle in its own window, so here the drawing is a preview of what the code does.

Change the numbers

4
120
90
import turtle
t = turtle.Turtle()

for i in range(4):
    t.forward(120)
    t.right(90)

Challenges0 of 3

  • Make a triangle: 3 sides, and turns that add up to 360 degrees.
  • Make a ten-point star: 10 lines that turn 108 degrees each time.
  • Make a flower with 10 circles that fill the whole turn.

Loop over things

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6Every item

The loop gives each item in the list the name fruit, one at a time.

Your turn: Add two more fruits to the list. How many times does All done print?

Python
for fruit in ["apple", "pear", "plum"]:
    print("I like", fruit)
print("All done")
Output
Press Run to see what it prints.

Watch a loop go round

Press Step to run one line at a time. Watch Python jump back up to the `for` line.

Ready. Press Step to run the first line.

  1. total = 0
  2. for coins in [3, 5, 2]:
  3. total += coins
  4. print("Total:", total)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Counting to three, three ways

The same loop, printing 0, 1 and 2, in Python and two other languages.

Language 1 of 2Python vs JavaScript

Python2 lines
for n in range(3):
    print(n)

Two lines. range(3) does the counting, and indentation marks the block.

JavaScript3 parts
for (let n = 0; n < 3; n++) {
  console.log(n);
}

JavaScript spells out the start, the check and the step, and uses curly brackets for the block.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.How many times does hi appear?

for n in range(3):
    print("hi")

0 of 6 answered

Common loop misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Doing something for every item

A for loop takes a collection of values and runs its block once for each value, in order. Each time round, called an iteration, the loop variable refers to the next value.

Try it 1: edit me, then Run
for fruit in ["apple", "pear", "plum"]:
    print("I like", fruit)
print("That is all")
Output
Press Run to see what it prints.

The loop body runs three times, with fruit set to "apple", then "pear", then "plum". The last line is not indented, so it runs once, after the loop finishes. The square brackets make a list, which has its own lesson soon; for now, read it as "these values, in this order".

Anything you can loop over is called iterable. Strings are iterable too: a for loop over a string gives one character at a time.

Try it 2: edit me, then Run
for letter in "hey":
    print(letter)
Output
Press Run to see what it prints.

Counting with range()

To repeat something a number of times, loop over range(). It produces whole numbers without storing them all, and it has three forms.

Try it 3: edit me, then Run
for i in range(3):          # 0, 1, 2
    print(i)
for i in range(2, 6):       # 2, 3, 4, 5
    print(i)
for i in range(10, 0, -3):  # 10, 7, 4, 1
    print(i)
Output
Press Run to see what it prints.

range(stop) starts at 0. range(start, stop) starts where you say. range(start, stop, step) jumps by step, which can be negative to count down. In every form the stop value is never included. This is why range(1, 6) gives 1 to 5: it is easy to remember as "up to but not including". The number of values in range(a, b) is simply b - a.

Patterns you will use constantly

Most loops follow one of a few patterns. A counter starts at 0 and adds 1 whenever something is found. An accumulator starts at an empty value and grows on every iteration.

Try it 4: edit me, then Run
prices = [3, 4, 5]
total = 0
for price in prices:
    total += price
print("Total:", total)

word = "banana"
count = 0
for letter in word:
    if letter == "a":
        count += 1
print("a appears", count, "times")
Output
Press Run to see what it prints.

The output is Total: 12 and a appears 3 times. Notice where each line sits. The starting value is set before the loop, the update happens inside it, and the result is printed after it. Putting total = 0 inside the loop would reset it every time; putting the print inside would show every step instead of the answer.

Strings can be accumulated the same way. Starting from "" and adding characters builds a new string, for example to reverse a word or remove its vowels.

A loop can also hold an if statement, as the letter counter does. That combination, visit every item and act only on some of them, is called filtering, and it is behind searches, reports and clean-up jobs everywhere. When you read an unfamiliar loop, ask three questions: what is being looped over, what changes on each pass, and what is the result once the loop ends. Answering them out loud is often enough to find a bug.

Positions with enumerate()

Sometimes you need the position as well as the item, for a numbered list or to know where something was found. enumerate() gives both, as a pair you unpack into two loop variables.

Try it 5: edit me, then Run
for number, task in enumerate(["wash up", "walk dog"], start=1):
    print(number, task)
Output
Press Run to see what it prints.

This prints 1 wash up and 2 walk dog. Without start=1 the count begins at 0, which is how Python numbers positions.

Two sequences at once with zip()

zip() walks two sequences side by side, giving one item from each on every iteration. It stops when the shorter one runs out.

Try it 6: edit me, then Run
names = ["Ana", "Bo"]
scores = [9, 7]
for name, score in zip(names, scores):
    print(f"{name}: {score}")
Output
Press Run to see what it prints.

Loops inside loops

A loop body can contain another loop. The inner loop runs completely for every single iteration of the outer one, which is exactly what you need for rows and columns, such as a times table.

Try it 7: edit me, then Run
for row in range(1, 4):
    line = ""
    for col in range(1, 4):
        line += f"{row * col:4}"
    print(line)
Output
Press Run to see what it prints.

This prints a 3 by 3 table. The inner loop builds one line, and the outer loop prints one line per row. Nine multiplications happen in total, three per row.

Good habits

Choose a loop variable name that describes one item: for price in prices reads better than for x in prices. Avoid changing a list while you loop over it; build a new one instead. And when you only need to repeat something and do not use the variable, the convention is to call it _, as in for _ in range(3):. The next lesson covers while loops, which repeat until a condition changes, and the break and continue statements, which work in both kinds of loop.

Syntax

The general shape of the statements in this lesson.

syntax.py
for item in collection:    # list, string, range ...
    ...
range(5)  range(1, 6)  range(10, 0, -2)   # stop is never included
for i, item in enumerate(items, start=1):
for a, b in zip(list_a, list_b):
total = 0                  # accumulator: set before,
for x in values:           # update inside,
    total += x
print(total)               # use after
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A shopping receipt

Beginner

Print each item of a basket with its number, and the total at the end, using enumerate() and an accumulator.

Python
items = ["bread", "milk", "eggs"]
prices = [1.2, 0.95, 2.1]
total = 0
for number, (item, price) in enumerate(zip(items, prices), start=1):
    print(f"{number}. {item:<6} {price:.2f}")
    total += price
print(f"Total: {total:.2f}")
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

zip() pairs each item with its price, and enumerate() numbers the pairs from 1. The parentheses in (item, price) unpack the pair inside the numbered value. The total is set before the loop, grows by one price on each iteration and is printed once after the loop ends.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

Expecting range to include the stop

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
for day in range(1, 7):
    print("Day", day)
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints days 1 to 6; day 7 is missing

Write this instead

for day in range(1, 8):
    print("Day", day)

Why it happens

range() always stops before the stop value.

In the real world

Where this shows up in software people use every day.

  1. Weekly step summary

    Health and fitness

    A walking app looks at a week of step counts and reports the total, the best day and how many days met the goal.

    Why Python fits

    One pass through the week updates three results at once: an accumulator for the total, a counter for goal days, and a running best. This is how many real reports are built.

    Python
    days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
    steps = [6200, 10400, 8100, 12050, 9900]
    GOAL = 10000
    total = 0
    goal_days = 0
    best_day = ""
    best = 0
    for day, count in zip(days, steps):
        total += count
        if count >= GOAL:
            goal_days += 1
        if count > best:
            best = count
            best_day = day
    print(f"Total: {total:,}")
    print(f"Goal met on {goal_days} days")
    print(f"Best day: {best_day}")
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

What value does the loop variable have after the loop?

The last value it was given. After for i in range(3):, i is 2. Do not rely on this in real code; it is clearer to keep the answer in its own variable.

Can I loop backwards over a string?

Yes: for letter in reversed(word): or for i in range(len(word) - 1, -1, -1):. The first is easier to read.

When should I use for and when while?

Use for when you know what to loop over, such as a list or a range. Use while when you repeat until something changes, which is the next lesson.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/5 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.