Sub topic 1
What a for loop can iterate over
A Python for loop does not care what kind of object it walks over, as long as the object is iterable. This chapter shows which objects qualify and what the loop variable receives from each of them.
Prerequisites
You should already know:
- Basic Python syntax: variables, indentation, and
print(). - What lists, strings, and integers are.
- How to write and run a Python 3 script.
Iterables
An iterable is any object that can hand out its items one at a time. The for statement asks the object for its items, assigns each one to the loop variable, and runs the indented body once per item.
Lists and strings
A list gives you its elements in order. A string gives you its characters in order, and each character is itself a string of length 1.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for ch in "abc":
print(ch)Tuples behave like lists here. Sets also work, but their order is not something to rely on.
Dictionaries
Looping over a dictionary gives you its keys. To get values or key-value pairs, call a method that returns a view of them.
ages = {"Ada": 36, "Grace": 45}
for name in ages:
print(name)
for age in ages.values():
print(age)
for name, age in ages.items():
print(name, age)In for name, age in ages.items(), each item is a pair, and Python unpacks it into the two variable names. Since Python 3.7, dictionaries keep insertion order, so the loops above print in the order the keys were added.
Other iterables
Many other objects are iterable. Common ones:
| Object | Items produced |
|---|---|
| `list`, `tuple` | Elements in order |
| `str` | Single characters |
| `dict` | Keys |
| `set` | Elements, in no guaranteed order |
| Open text file | Lines, including the trailing newline |
| `range(...)` | Integers, covered in the next chapters |
You can check whether an object is iterable by passing it to iter(). A non-iterable raises TypeError.
for n in 5:
print(n)This fails with TypeError: 'int' object is not iterable. An integer is a single value, not a collection of items. This is the most common error at this stage. If you meant to count from 0 to 4, you need an object that produces those numbers, and that is the job of range().
Summary of the model
The loop needs one thing from the object after in: the ability to produce items one by one. Everything else about the object is irrelevant to the loop. Later chapters explain how this works internally with iter() and next().
Exercise
What does the following code print, and why? d = {"x": 1, "y": 2} for item in d: print(item)
Show answer
It prints x and then y. Looping over a dictionary yields its keys. To get the values use d.values(), and to get both use d.items().
Exercise
What error does for i in 3.5: raise, and what is the cause?
Show answer
It raises TypeError: 'float' object is not iterable. A float is a single value and cannot supply items one at a time.