Python for Loops
Beginner Control Flow

Python for Loops

1Python for Loops: overview

A for loop runs the same block of code once for every item in a collection, giving the current item a name while its turn runs.

GoalBy the end you can loop over lists, strings and range(), number items with enumerate(), stop early with break, skip items with continue, and build a running total.

Before this lesson: Python Variables, Python if, elif and else

2Python for Loops: diagram

Python for Loopsscores = [7, 9, 4]for s in scores:any item left? take ityes: s = 7, 9, 4loop body runstotal += safter the last itemafter the loopprint(total)next item
The for statement hands the body one item at a time. When the body finishes, Python goes back for the next item; once there are none left, it carries on with the code after the loop.

3Python for Loops: explained step by step

A for loop lets you write an action once and have Python repeat it for every item in a collection. You don't need to keep a counter or decide when to stop: the loop ends by itself when it runs out of items.

Python
for name in ["Asha", "Ben", "Chen"]:
    print("Hello,", name)
print("Everyone greeted")

The line ending in a colon is the loop header. The indented lines under it form the loop body. Each pass through the body is called an iteration, and on each one the loop variable (name here) holds the current item. The unindented print runs once, after the loop has finished.

What can you loop over?

Anything Python can hand out one piece at a time, called an iterable: lists, tuples, strings (one character at a time), dictionaries, sets, files and range().

Counting with range()

When you want to repeat something a set number of times, or you need the numbers themselves, use range(). range(3) produces 0, 1, 2: it stops before the end value, just like slicing does. range(1, 6) gives 1 to 5, and a third argument sets the step.

Python
for i in range(3):
    print("Round", i)

for n in range(10, 0, -3):
    print(n)

Index and item together: enumerate()

If you need each item's position too, wrap the collection in enumerate(). It gives you (index, item) pairs that you unpack straight into two variables. Pass start=1 when you want human-friendly numbering. This is clearer and safer than juggling range(len(items)) and indexes by hand.

break and continue

break stops the loop immediately, which is useful once you've found what you were searching for. continue skips the rest of the body for the current item and moves on to the next one.

Python
readings = [18, 21, -1, 25, 40, 19]
for t in readings:
    if t == -1:
        continue      # faulty sensor value: skip it
    if t > 35:
        print("Too hot, stopping at", t)
        break
    print("OK:", t)

The accumulator pattern

A very common job is to combine all the items into one result: a total, a count, the longest word. Create the result variable before the loop, update it inside the loop, and use it after the loop. You'll see this pattern in nearly every program you write.

Quick reference: Python for Loops

4Python for Loops: syntax

for item in iterable:
    # body: runs once per item

for i in range(stop):                  # 0, 1, ..., stop - 1
for i in range(start, stop, step):
for index, item in enumerate(items, start=1):

break       # leave the loop right now
continue    # skip to the next item

5Python for Loops: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
scores = [72, 95, 58, 88, 64]

total = 0
for score in scores:
    total += score
print("Average:", total / len(scores))

for position, score in enumerate(scores, start=1):
    if score < 60:
        print(f"Student {position} needs help ({score})")
        continue
    print(f"Student {position} passed ({score})")

for score in scores:
    if score >= 90:
        print("First top score found:", score)
        break
Expected outputAverage: 75.4
Student 1 passed (72)
Student 2 passed (95)
Student 3 needs help (58)
Student 4 passed (88)
Student 5 passed (64)
First top score found: 95

7Python for Loops: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1A list of five test scores is stored in scores.
  2. Line 3The accumulator total starts at 0 before the loop, so it is created only once.
  3. Line 4-5The loop runs five times. Each time, score holds the next value and gets added to total, which ends at 377.
  4. Line 6This line is not indented, so it runs once, after the loop: 377 / 5 = 75.4.
  5. Line 8enumerate(scores, start=1) hands out pairs like (1, 72), unpacked into position and score.
  6. Line 9-11For a score under 60, a help message is printed and continue jumps straight to the next student, skipping line 12.
  7. Line 12Every student who did not hit continue gets the "passed" line.
  8. Line 14-17The last loop searches for the first score of 90 or more. It finds 95 on the second item, prints it, and break ends the loop without checking the rest.

8Python for Loops: common mistakes

Expecting range() to include the end value

✗ Wrong

for day in range(1, 7):
    print("Day", day)
Prints Day 1 to Day 6 — Day 7 is missing

✓ Right

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

range() stops just before the end value. To count from 1 to 7, the end must be 8.

Resetting the total inside the loop

✗ Wrong

prices = [5, 10, 15]
for p in prices:
    total = 0
    total += p
print(total)
Prints 15 instead of 30 — the total starts again from 0 on every item

✓ Right

prices = [5, 10, 15]
total = 0
for p in prices:
    total += p
print(total)

Create the accumulator once, before the loop. Only the update belongs inside the body.

Changing the loop variable to change the list

✗ Wrong

prices = [10, 20, 30]
for p in prices:
    p = p * 2
print(prices)
Prints [10, 20, 30] — the list is unchanged

✓ Right

prices = [10, 20, 30]
for i, p in enumerate(prices):
    prices[i] = p * 2
print(prices)

The loop variable is just a name for the current item. Giving it a new value doesn't touch the list. Use enumerate() to get the index and assign to prices[i] (or build a new list).

9Python for Loops: exercises

Write your answer, then press Check. The checks run in your browser.

1. Add up the cart

Write code Easy

Use a for loop (not sum()) to add up all the prices in prices. Store the result in total, then print it.

Your code
prices = [12.5, 3.0, 7.25, 20.0]
total = 0

# loop over prices and add each one to total

2. Predict break and continue

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
for n in range(1, 10):
    if n == 7:
        break
    if n % 2 == 0:
        continue
    print(n)
print("done")

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

When should I use a for loop instead of a while loop?

Use a for loop when you know what you are looping over: the items of a collection or a fixed number of repetitions. Use a while loop when you must keep going until some condition changes and you can't tell in advance how many rounds that will take.

How do I get the index in a Python for loop?

Wrap the collection in enumerate(): for i, item in enumerate(items): gives you the position and the item together. Add start=1 if you want counting to begin at 1.

Why does range(5) stop at 4?

range() stops just before its end value, so range(5) gives exactly five numbers: 0, 1, 2, 3, 4. Those are also the valid indexes of a five-item list, which is why this convention is so handy.

Further reading

10Next lesson

Up nextPython while LoopsA while loop keeps repeating a block of code for as long as its condition is True, checking the condition again before …

Related:
Python range() FunctionPython break and continuePython enumerate() and zip()Python Lists

← Python match Statement · All Control Flow lessons · Practise in the IDE