Sub topic 2
The for statement
This chapter assumes you know basic Python syntax (variables, indentation, print()), lists, strings and integers, and how to run a Python 3 script.
The working model
A for statement runs a block of code once for each item produced by an iterable. An iterable is any object you can walk through one item at a time, such as a list, string, tuple, dictionary, set, or file.
for variable in iterable:
bodyThree parts matter:
- The loop variable is a name that Python assigns each item to, in order.
- The iterable is the source of items. Python asks it for the next item until none are left.
- The body is the indented block. It runs once per item.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for ch in "abc":
print(ch)The first loop prints each fruit on its own line. The second prints a, b and c, because iterating over a string yields one character at a time.
Iterating over other types
The item you get depends on the type of the iterable.
| Iterable | Each item is |
|---|---|
| list, tuple | an element |
| string | a one-character string |
| dictionary | a key |
| set | an element, in no guaranteed order |
Dictionaries are the usual surprise. A plain loop gives you keys, not values. Use .values() or .items() for the rest.
ages = {"Ada": 36, "Grace": 45}
for name in ages:
print(name)
for name, age in ages.items():
print(name, age)The second loop unpacks each (key, value) pair into two loop variables. You can unpack any item that is itself a sequence of the right length.
Common errors
- Missing colon or indentation. The
forline must end with:, and the body must be indented. Without a body you get anIndentationError. - Iterating over a number.
for i in 5:raisesTypeError: 'int' object is not iterable. An integer is not a collection. To repeat something five times, userange(5), which a later chapter covers. - Expecting values from a dictionary.
for x in agesgives keys. If you need values, ask for them explicitly. - Reusing a name. The loop variable is an ordinary variable. If you already have
fruitholding something important, the loop overwrites it.
Reading a loop
When you read a for loop, ask two questions: what is the iterable, and what does one item look like? Once you know both, the body is easy to follow. If you are unsure, print type(item) inside the loop and run it on a small input.
Exercise
Given scores = {"Ada": 95, "Grace": 88}, what does for x in scores: print(x) print, and how would you print the numbers instead?
Show answer
It prints the keys, Ada and Grace. To print the numbers, loop over scores.values(), as in for x in scores.values(): print(x).
Exercise
Why does for i in 10: print(i) fail, and what error does Python raise?
Show answer
An integer is not iterable, so Python raises TypeError: 'int' object is not iterable. A loop needs an object that can produce a sequence of items, such as a list or a range.