Sub topic 1
What a for loop can iterate over
A Python for loop does not work only on lists. It works on any object that can hand out its items one at a time. This chapter explains what that means in practice, which built-in types qualify, and what happens when you loop over something that does not.
Prerequisites
This chapter assumes you can do the following:
- Use variables, indentation, and
print()in a Python 3 script. - Create lists, strings, and integers, and know roughly what each one holds.
- Run a script from the command line or an editor.
You do not need to know how range() works yet. The next chapters cover it.
Iterables and sequences
An iterable is any object a for loop can take items from. A sequence is a narrower idea: an ordered collection whose items you can reach by position, such as my_list[0]. Every sequence is iterable, but not every iterable is a sequence.
| Type | Iterable? | Sequence? | What the loop produces |
|---|---|---|---|
| `list`, `tuple` | Yes | Yes | Items in order |
| `str` | Yes | Yes | One-character strings |
| `range` | Yes | Yes | Integers |
| `dict` | Yes | No | Keys, in insertion order |
| `set`, `frozenset` | Yes | No | Items in no guaranteed order |
| File object | Yes | No | Lines of text |
| Generator | Yes | No | Values computed on demand |
| `int`, `float`, `None` | No | No | Raises `TypeError` |
Lists and tuples
These are the simplest case. The loop variable takes each item in turn, in order.
colors = ("red", "green", "blue")
for color in colors:
print(color)The loop runs once per item, so the body here runs three times. The loop variable is just a name bound to the current item. You choose the name, and a singular noun for a plural collection reads well.
Strings
A string is a sequence of characters. Looping over it gives you one-character strings. Python has no separate character type.
word = "café"
for ch in word:
print(ch)This prints four lines, because Python 3 iterates over Unicode code points, not bytes. A single visible symbol made of a base letter plus a combining accent can still show up as two items, so do not assume one loop pass equals one symbol on screen.
Dictionaries
Looping over a dictionary gives you its keys. Since Python 3.7, keys come out in the order they were inserted.
prices = {"tea": 3, "coffee": 4, "juice": 5}
for key in prices:
print(key)
for value in prices.values():
print(value)
for key, value in prices.items():
print(key, "costs", value)The .keys(), .values(), and .items() methods return views, which are iterable objects tied to the dictionary. .items() produces pairs, and the loop header key, value unpacks each pair into two names. Unpacking works for any iterable whose items are themselves pairs or longer groups.
points = [(1, 2), (3, 4), (5, 6)]
for x, y in points:
print(x + y)The number of names must match the size of each item. Otherwise Python raises a ValueError.
Sets
A set is iterable, but it has no meaningful order. Two runs of the same program can print string items in different orders, because Python randomizes string hashing for each process.
tags = {"python", "loops", "range"}
for tag in sorted(tags):
print(tag)If the order matters to your output or your tests, wrap the set in sorted(). It accepts any iterable and returns a new list.
Files and other lazy sources
A file object yields one line per pass, including the trailing newline character. The file is read as you go, so a huge file does not have to fit in memory. This example uses io.StringIO, an in-memory file-like object, so it runs without any file on disk.
import io
source = io.StringIO("first\nsecond\nthird\n")
for line in source:
print(line.rstrip("\n"))With a real file, you would write with open("notes.txt") as f: and loop over f in the same way.
A generator is another lazy source. It computes each value only when the loop asks for it.
def squares(limit):
for n in range(limit):
yield n * n
for value in squares(4):
print(value)One-shot iterables
Lists, tuples, strings, and dictionaries can be looped over as many times as you like. Generators, files, and other iterator objects cannot. They are exhausted after one full pass, and a second loop sees nothing.
gen = (n * 2 for n in [1, 2, 3])
print(list(gen)) # [2, 4, 6]
print(list(gen)) # []What happens when the object is not iterable
If the object after in cannot produce items, Python stops with a TypeError before the body runs.
try:
for digit in 12345:
print(digit)
except TypeError as err:
print(err) # 'int' object is not iterableA frequent cause is expecting a number to behave like a sequence of digits. To loop over the digits, convert it first with str(12345). Another frequent cause is a function that returns None when it finds nothing, and the caller then loops over its result.
Checking whether something is iterable
You can ask Python directly. The collections.abc.Iterable class recognizes any object that defines the iteration method.
from collections.abc import Iterable
for obj in [[1, 2], "hi", 42, None, {"a": 1}]:
print(repr(obj), isinstance(obj, Iterable))Calling iter(obj) and catching TypeError also works, and it is the most reliable test, because it asks the same question the loop asks.
Changing a collection while looping
Iterating gives you a live view of the collection, not a snapshot. For dictionaries and sets, adding or removing items during the loop raises RuntimeError.
stock = {"apple": 3, "pear": 0, "plum": 2}
for name in list(stock): # list() copies the keys first
if stock[name] == 0:
del stock[name]
print(stock) # {'apple': 3, 'plum': 2}Looping over list(stock) makes a copy of the keys, so deleting from the dictionary is safe. Lists do not raise an error in the same situation. They skip items silently, which is worse. A later chapter covers that trap in detail.
Common mistakes
- Looping over a dictionary and expecting values. You get keys unless you call
.values()or.items(). - Relying on set order. Sort first when order matters.
- Looping over a string of digits and treating each item as a number. Each item is a string such as
"7". - Reusing an exhausted generator or file.
- Passing
Noneor an integer tofor.
Exercise
What does this code print, and why? for k in {"a": 1, "b": 2}: print(k)
Show answer
It prints a and then b, each on its own line. Looping over a dictionary produces its keys in insertion order, not its values. To get the values you would loop over .values(), and to get both you would loop over .items().
Exercise
You write data = (line.strip() for line in open("log.txt")) and then loop over data twice. The second loop does nothing and raises no error. Why, and how do you fix it?
Show answer
A generator expression produces a one-shot iterator. The first loop consumes every item, so the second finds it exhausted and runs zero times. Fix it by building a list, as in data = [line.strip() for line in open("log.txt")], or by creating a new generator for each loop.
Exercise
Write a loop that prints each key and value of the dictionary {"x": 10, "y": 20} on one line, such as x = 10.
Show answer
for key, value in {"x": 10, "y": 20}.items(): print(key, "=", value)