Sub topic 2
The for statement
A for statement runs a block of code once for each item an iterable produces. This chapter covers the syntax, what you can loop over, how the loop variable behaves, and the errors intermediate learners hit most often. It assumes you can write and run a Python 3 script, and that you know variables, indentation, print(), and the basic behavior of lists, strings, and integers.
The shape of a for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for ch in "abc":
print(ch)A for statement has four parts:
- The keyword
for. - A target, here
fruitorch, which receives each item. - The keyword
in, followed by an iterable, which is any object that can hand out its items one at a time. - A colon and an indented body.
Python takes the first item and assigns it to the target. It runs the body, then takes the next item and runs the body again. When the iterable has no items left, the loop ends and execution continues at the first line after the indented block.
Python does not track a counter or an index for you. The loop only asks the iterable for "the next item" until none are left. This is why the same syntax works for lists, strings, dictionaries, files, and many other objects.
What a for loop can iterate over
An iterable is any object you can loop over. The built-in types you will meet most often are these:
| Iterable | Items produced |
|---|---|
| `list`, `tuple` | The elements, in order |
| `str` | One-character strings |
| `dict` | The keys, in insertion order |
| `set` | The elements, in no guaranteed order |
| `range` | Integers (covered in the next chapters) |
| An open text file | One line at a time, including the newline |
Strings produce strings, not a separate character type. Each ch in the earlier example is a str of length 1.
Looping over a dictionary
Iterating over a dictionary gives you its keys. This surprises many learners, who expect key-value pairs.
prices = {"apple": 0.5, "banana": 0.25, "cherry": 3.0}
for name in prices:
print(name)
for price in prices.values():
print(price)
for name, price in prices.items():
print(name, price)Use .values() when you only need the values. Use .items() when you need both. .items() produces (key, value) tuples, and the target name, price unpacks each tuple.
Unpacking in the target
The target does not have to be a single name. If each item is a sequence of a known length, you can unpack it directly in the for line.
points = [(0, 0), (2, 5), (4, 1)]
for x, y in points:
print("x =", x, "y =", y)The number of names must match the length of each item. If it does not, Python raises ValueError, for example too many values to unpack (expected 2).
Things that are not iterable
An integer is not iterable, so this fails:
count = 5
for i in count:
print(i)Python raises TypeError: 'int' object is not iterable. If you meant to repeat something five times, you need a sequence of five items. Producing one is the job of range(), the subject of the next chapters.
The loop variable
The target is an ordinary variable. It lives in the enclosing scope, which is the function or module that contains the loop. A for loop does not create its own scope. Two consequences follow.
First, the variable keeps its last value after the loop ends.
for i in range(3):
pass
print(i) # 2: the loop variable is still bound after the loopSecond, if the iterable is empty, the body never runs and the variable is never assigned. Using it afterward raises NameError unless it was defined earlier.
for j in range(0):
pass
# print(j) would raise NameError, because the body never ranBecause the variable survives, reusing a name that already held something can overwrite it. If you wrote total = 10 and later used for total in prices:, the original value of total is gone.
Reassigning the variable does not change the loop
At the top of each iteration, Python assigns the next item to the target, regardless of what the body did to it.
for n in [1, 2, 3]:
print("before:", n)
n = n * 100
print("after:", n)Each pass prints the original item first (1, then 2, then 3). Changing n inside the body has no effect on which item comes next.
Rebinding the name is different from mutating the object it refers to. If the items are mutable, such as lists, changing them in place does change the original data.
rows = [[1], [2], [3]]
for row in rows:
row.append(0)
print(rows) # [[1, 0], [2, 0], [3, 0]]Here row refers to the same list object that sits inside rows, so append modifies it. Assigning row = row + [0] would build a new list and leave rows unchanged.
Iterables you can only use once
Lists, tuples, strings, dictionaries, and ranges can be looped over as many times as you like. Some iterables are one-shot. Looping over them consumes them. Files and generators are the common cases.
squares = (n * n for n in [1, 2, 3])
for s in squares:
print(s) # 1, 4, 9
for s in squares:
print(s) # prints nothing: already exhaustedThe second loop does not fail. It simply finds nothing left and runs zero times. If you need to loop twice, store the items in a list first: squares = list(squares). Silent empty loops like this are a frequent source of "my code ran but did nothing" bugs.
A worked example
This function reads a list of order totals, skips invalid entries, and computes a total, using only what this chapter covers.
def sum_valid(orders):
total = 0
for order in orders:
if order is None:
continue
total += order
return total
print(sum_valid([10, None, 5, 2.5])) # 17.5
print(sum_valid([])) # 0Notes on the design:
totalis defined before the loop, so the function returns a sensible value even whenordersis empty.continueskips the rest of the body for that item and moves to the next one. The next chapters coverbreakandcontinuein detail.- The loop never touches an index, so it works equally well with a list, a tuple, or a generator.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `SyntaxError: expected ':'` | Missing colon after the `for` line | Add `:` at the end of the line |
| `IndentationError: expected an indented block` | Empty or unindented body | Indent the body, or use `pass` as a placeholder |
| `TypeError: 'int' object is not iterable` | Looping over a number | Loop over a sequence, such as a `range` |
| `ValueError: too many values to unpack` | Target names do not match item length | Match the number of names to the item |
| Variable still set after loop, or `NameError` | Loop variable lives in the enclosing scope | Do not rely on it after the loop unless the iterable is non-empty |
| Second loop does nothing | One-shot iterator already consumed | Convert to a list first |
Exercises
Exercise
Given scores = {"Ada": 95, "Grace": 88, "Linus": 72}, write a loop that prints each name and score on one line, for example Ada 95. Then say what for x in scores: assigns to x.
Show answer
Use for name, score in scores.items(): print(name, score). A plain for x in scores: assigns each key to x, so x takes the values "Ada", "Grace", and "Linus" in insertion order.
Exercise
What does this code print, and why? for n in [1, 2, 3]: n = n + 10 print(n)
Show answer
It prints 13. Each pass assigns the next list item to n, and the body rebinds n to a new value without affecting the list or the iteration. After the last pass, n is still bound in the enclosing scope, and its last value is 3 + 10 = 13.