Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 149 ยท Control Flow

for Loops

Learn Python for loops step by step. Iterate over strings, lists and dictionaries, number items with enumerate(), pair them with zip() and nest loops safely.

Programs often need to do the same thing for every item in a collection: print each name on a guest list, add up every price on a receipt, check each word in a sentence. Writing one line per item would be tedious and would break the moment the collection changed size. A loop solves this by running a block of code once for each item.

Python's for loop is built for exactly this job. Instead of counting with an index the way many older languages do, it hands you the items themselves, one at a time. That makes Python loops short, readable and hard to get wrong. In this lesson you'll loop over strings, lists and dictionaries, number items with enumerate(), walk two collections side by side with zip(), and put one loop inside another.

The shape of a for loop

A for loop has a header line and an indented body:

Python
for item in collection:
    do_something_with(item)
  • for and in are keywords.
  • item is a loop variable. You choose its name. On each pass, Python assigns the next value from the collection to it.
  • The colon ends the header, and the indented lines below it form the body, exactly like an if statement.
  • Each run of the body is called an iteration.

When the collection runs out of items, the loop ends and Python continues with the first line after the body.

Python Looping over a list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last print() is not indented, so it runs once, after the loop has finished. Try indenting it by four spaces and run again: now it runs on every iteration.

Tip: Pick a loop variable name that describes one item. A plural collection name with a singular loop variable, such as for planet in planets, reads like a sentence.

What can you loop over?

Anything Python calls iterable works after in. You'll meet many iterables in this course, but the everyday ones are:

Iterable Each iteration gives you
A string One character
A list or tuple One element, in order
A set One element, in no guaranteed order
A dictionary One key
range(n) One number: 0, 1, 2, โ€ฆ up to n โˆ’ 1
A file object One line of text

Strings are a nice example because the result surprises many beginners: you get characters, not words.

Python Strings and dictionaries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Looping over a dictionary directly gives you its keys. When you need both the key and the value, .items() produces pairs, and writing for fruit, count in ... unpacks each pair into two variables. You'll learn more about this in Dictionaries and Unpacking.

Building a result inside a loop

A very common pattern is the accumulator: create a variable before the loop, then update it on every iteration.

Python Totals and filtered lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The two accumulators here are a number (total) and a list (expensive). Initialize them before the loop. If you put total = 0 inside the body, it would reset on every pass and you'd end up with only the last price.

For simple totals, Python has built-ins that do the looping for you: sum(prices), max(prices) and min(prices). Use them when they fit. Write your own loop when the logic is more specific than "add everything".

Counting with enumerate()

Sometimes you need the position of each item as well as the item, for example to number a list for display. Beginners coming from other languages often write for i in range(len(items)) and then use items[i]. It works, but Python has a cleaner tool: enumerate().

enumerate() wraps any iterable and produces pairs of (index, item):

Python Numbered lists with enumerate()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Counting starts at 0 by default, matching list indexes. Pass start=1 when the numbers are meant for people. The start value only changes the numbers you see; it doesn't skip any items.

Walking two collections with zip()

When two lists line up, such as names and scores recorded in the same order, zip() pairs their items like the teeth of a zipper:

Python Pairing items with zip()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that "Thu" never appears: zip() stops as soon as any input runs out. That quiet behavior can hide bugs when lists should be the same length. Since Python 3.10 you can write zip(days, temps, strict=True), which raises a ValueError if the lengths differ. Try adding strict=True to the second loop above.

zip() accepts any number of iterables, and you can combine it with enumerate():

Python
for rank, (player, score) in enumerate(zip(players, scores), start=1):
    print(rank, player, score)

The parentheses around (player, score) are required here, because each item from enumerate() is a pair whose second part is itself a pair.

Nested loops

The body of a loop can contain another loop. The inner loop runs completely for every single iteration of the outer loop.

Python A multiplication grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The outer loop runs 5 times and the inner loop runs 5 times per outer pass, so the innermost line runs 25 times. That multiplication matters: two nested loops over 1,000 items each run the body a million times. Nested loops are perfect for grids, tables and comparing every item with every other item, but keep their cost in mind with big data.

Nested data often calls for nested loops too:

Python Looping through nested data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

Warning: Don't add or remove items from a list while a for loop is iterating over that same list. The loop tracks its position by index, so items get skipped or visited twice. Loop over a copy (for x in items[:]) or build a new list instead.

  • Forgetting the colon at the end of the header gives a SyntaxError.
  • Inconsistent indentation in the body gives an IndentationError or, worse, a line that silently runs outside the loop.
  • Reassigning the loop variable doesn't change the list. for n in numbers: n = n * 2 updates the local name n only; the list stays the same. To transform a list, build a new one (see List Comprehensions).
  • Expecting the loop variable to vanish. After the loop ends, the variable still holds the last value it was given. That's occasionally useful, but don't rely on it if the collection might be empty: the variable is never created then.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does for ch in "hi!": print(ch) print?

    Looping over a string gives one character per iteration, so the body runs three times.
  2. 2. Which loop prints 1. red, 2. green, 3. blue for colors = ["red", "green", "blue"]?

    enumerate(colors, start=1) yields (1, "red"), (2, "green") and so on, which unpack into i and c. Without start=1 the numbers begin at 0.
  3. 3. How many lines does for a, b in zip([1, 2, 3], ["x", "y"]): print(a, b) print?

    By default zip() stops at the shortest input, so only two pairs are produced. Add strict=True if you want a length mismatch to raise a ValueError.
  4. 4. What does looping directly over a dictionary give you?

    Iterating a dict yields its keys in insertion order. Use .values() for values or .items() for (key, value) pairs.
  5. 5. In a loop of 10 iterations that contains another loop of 4 iterations, how many times does the inner body run?

    The inner loop runs all 4 iterations for each of the 10 outer iterations, so 10 ร— 4 = 40.

Summary

  • for item in iterable: runs its indented body once per item, assigning each item to the loop variable.
  • Strings give characters, lists and tuples give elements, dictionaries give keys (.items() gives pairs).
  • Create accumulators such as total = 0 or results = [] before the loop and update them inside it.
  • enumerate(items, start=1) gives you a counter alongside each item; prefer it over range(len(items)).
  • zip(a, b) walks collections in step and stops at the shortest; strict=True turns a length mismatch into an error.
  • Nested loops multiply: the inner body runs (outer count ร— inner count) times.
  • Don't modify a list while looping over it.

Next: while Loops, where you'll repeat code for as long as a condition stays true.