Sub topic 1
Iterables and iterators: what a for loop consumes
Every for loop in Python works the same way. The loop asks an object for a stream of values and takes them one at a time until the stream ends. Once you know how that request works, enumerate and zip stop looking like special syntax. They are ordinary functions that take iterables, and their results plug into the same machinery.
This chapter builds that working model. It covers the two protocols behind for, the difference between an iterable and an iterator, and the errors that follow when the two are confused.
Prerequisites
This chapter assumes you can:
- Write basic Python syntax, including functions,
ifstatements, andtry/except. - Write a
forloop over a list. - Work with lists, tuples, and dictionaries.
- Call a function and use its return value.
You do not need to know about generators or classes in depth. A short class example appears later, and you can skim it on a first read.
What a for loop actually does
Here is a plain loop:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Python runs it roughly as the following code does. This version does the same work by hand:
fruits = ["apple", "banana", "cherry"]
iterator = iter(fruits)
while True:
try:
fruit = next(iterator)
except StopIteration:
break
print(fruit)The loop makes two kinds of calls:
- It calls
iter()once on the object afterin. The result is an iterator. - It calls
next()on that iterator again and again. Each call returns the next value. When no values are left, the iterator raisesStopIteration. The loop catches this exception silently and exits.
The loop variable (fruit) is assigned each value that next() returns. The StopIteration exception is how an iterator signals "I am finished". It is not an error, and a for loop never shows it to you.
Iterable versus iterator
The two words name different roles, and mixing them up causes most of the confusion in this area.
- An iterable is an object you can loop over. It supports
iter(), which means it defines an__iter__method. Lists, tuples, strings, dictionaries, sets, ranges, and files are iterables. - An iterator is an object that produces values one at a time and remembers where it is. It supports
next(), which means it defines a__next__method. It also defines__iter__, and that method returns the iterator itself.
Every iterator is an iterable, but most iterables are not iterators.
| Property | Iterable | Iterator |
|---|---|---|
| Supports `iter(obj)` | Yes | Yes (returns itself) |
| Supports `next(obj)` | Usually no | Yes |
| Remembers a position | No | Yes |
| Can be looped over twice | Usually yes | No, it is used up after one pass |
| Examples | `list`, `str`, `dict`, `range` | `iter([1, 2])`, `enumerate(...)`, `zip(...)`, generators |
The iter() call on a list builds a new iterator each time, and that iterator holds the position. The list itself holds no position. This is why you can loop over the same list as many times as you like. Each loop gets a fresh iterator.
fruits = ["apple", "banana", "cherry"]
it = iter(fruits)
print(type(fruits))
# <class 'list'>
print(type(it))
# <class 'list_iterator'>
print(next(it))
# apple
print(next(it))
# banana
print(next(it))
# cherry
try:
next(it)
except StopIteration:
print("done")
# doneCalling next() on the list directly fails, because the list is an iterable but not an iterator:
fruits = ["apple", "banana", "cherry"]
try:
next(fruits)
except TypeError as error:
print(error)
# 'list' object is not an iteratorAn iterator's iter() returns the iterator itself, while a list's iter() returns a new object each time. The identity test below shows the difference:
fruits = ["apple", "banana", "cherry"]
it = iter(fruits)
print(iter(fruits) is fruits)
# False
print(iter(it) is it)
# TrueThe second line explains why you can pass an iterator to a for loop. The loop calls iter() on it, gets the same object back, and carries on from wherever it stands.
Checking what you have
The collections.abc module defines Iterable and Iterator as types you can test against with isinstance:
from collections.abc import Iterable, Iterator
samples = ([1, 2], "hi", {"a": 1}, range(3), iter([1]), 42)
for obj in samples:
print(type(obj).__name__, isinstance(obj, Iterable), isinstance(obj, Iterator))
# list True False
# str True False
# dict True False
# range True False
# list_iterator True True
# int False FalseThe int row is the one that produces a common error. A for loop over a number fails because integers do not support iter():
try:
for digit in 123:
print(digit)
except TypeError as error:
print(error)
# 'int' object is not iterableIf you meant to loop over the digits, loop over str(123) instead. If you meant to loop that many times, loop over range(123).
What counts as an iterable
Many everyday objects are iterables, and each one decides for itself what its values are:
- Strings produce one character at a time.
- Dictionaries produce their keys. Use
.values()or.items()for values or key/value pairs. - Ranges produce integers on demand without storing them all.
- Files produce one line at a time, so a loop over a file never holds the whole file in memory.
- Sets produce their elements in an order you should not rely on.
- Generators and generator expressions are iterators that compute each value when asked.
prices = {"apple": 0.5, "banana": 0.25}
for key in prices:
print(key)
# apple
# banana
for key, value in prices.items():
print(key, value)
# apple 0.5
# banana 0.25The .items() call returns a view whose values are (key, value) tuples. The loop header unpacks each tuple into two names. Unpacking has its own chapter in this tutorial, so for now it is enough to see that the loop receives one tuple per step.
You can also make your own iterables. The simplest way is to write __iter__ as a generator function:
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
counter = Countdown(3)
print(list(counter))
# [3, 2, 1]
print(list(counter))
# [3, 2, 1]Countdown is an iterable but not an iterator. Each call to iter(counter) runs __iter__ again and returns a new generator that starts from the top. That is why the second list(counter) gives the full result again.
An object that is its own iterator must keep its position and raise StopIteration itself:
class CountdownIterator:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
counter = CountdownIterator(3)
print(list(counter))
# [3, 2, 1]
print(list(counter))
# []This version is used up after one pass. The position lives in the object, and nothing resets it.
Iterators are used up
Because an iterator stores a position that only moves forward, it can be consumed only once. After the last value, it stays empty:
squares = (n * n for n in range(4))
print(list(squares))
# [0, 1, 4, 9]
print(list(squares))
# []The second list() does not raise an error. It produces an empty list, because the generator has nothing left to give. This silent failure is the main hazard of working with iterators, and a later chapter returns to it with enumerate and zip.
The same fact has a useful side. Since a for loop calls iter() on an iterator and gets the same object back, you can stop a loop partway and continue from where you left off:
it = iter(["a", "b", "c", "d"])
for letter in it:
print(letter)
if letter == "b":
break
print("resumed:")
for letter in it:
print(letter)
# a
# b
# resumed:
# c
# dRun the same code on a list instead of iter(list), and the second loop would start over from "a".
Pulling single values with next
The built-in next() takes one value without writing a loop. Its optional second argument is a default, which next() returns instead of raising StopIteration when the iterator is empty:
it = iter([10, 20])
print(next(it))
# 10
print(next(it))
# 20
print(next(it, "empty"))
# emptyA common use is taking the first match from a stream:
numbers = [3, 8, 11, 14]
first_even = next((n for n in numbers if n % 2 == 0), None)
print(first_even)
# 8Partial consumption affects what is left
Any code that pulls from an iterator changes what remains for everyone else sharing it. Here, next() removes the header line before the loop sees the rest:
lines = iter(["name,score", "Ada,95", "Grace,88"])
header = next(lines)
print(header)
# name,score
for line in lines:
print(line)
# Ada,95
# Grace,88This pattern is common when reading files, because a file object is its own iterator.
Lists change under their iterators
A list iterator stores an index into the list, not a copy of it. If the loop body changes the list, the index and the list can disagree. This code tries to remove the even numbers:
numbers = [2, 4, 6, 7]
for n in numbers:
if n % 2 == 0:
numbers.remove(n)
print(numbers)
# [4, 7]The result still contains 4. After the first removal, 4 slides into position 0, but the iterator's next index is 1, so 4 is skipped. The safe options are to loop over a copy (for n in numbers[:]) or to build a new list:
numbers = [2, 4, 6, 7]
odds = [n for n in numbers if n % 2 != 0]
print(odds)
# [7]Dictionaries are stricter. Adding or removing keys during a loop over them raises RuntimeError: dictionary changed size during iteration.
Why this matters for enumerate and zip
The built-ins enumerate and zip fit this model exactly:
- They accept iterables as input. They call
iter()on each argument. - They return iterators, not lists. Values are produced one pair at a time as the loop asks for them.
You can verify this with the tools from this chapter:
pairs = enumerate(["a", "b"])
print(type(pairs).__name__)
# enumerate
print(iter(pairs) is pairs)
# True
print(next(pairs))
# (0, 'a')
print(list(pairs))
# [(1, 'b')]The list(pairs) call returns only the second pair, because next() already consumed the first. The zip function behaves the same way:
combined = zip([1, 2, 3], ["x", "y", "z"])
print(type(combined).__name__)
# zip
print(iter(combined) is combined)
# TrueEach result is a tuple, and a for loop gives you one tuple per step. The next chapters show how to name the parts of those tuples directly in the loop header, and how enumerate and zip replace manual index counters.
Because they accept any iterable, these functions also work on inputs that have no length or indexing, such as files and generators. A loop written as for i in range(len(seq)) requires seq to support len() and indexing. A loop written with enumerate(seq) requires only that seq be iterable.
def numbered(lines):
for number, line in enumerate(lines):
print(number, line)
numbered(["first", "second"])
# 0 first
# 1 second
numbered(text.upper() for text in ["third", "fourth"])
# 0 THIRD
# 1 FOURTHThe same function accepts a list and a generator expression. An index-based version would fail on the generator, because generators have no len().
Common errors, summarized
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: 'int' object is not iterable` | The loop target does not support `iter()` | Loop over `range(n)` or `str(n)` as intended |
| `TypeError: 'list' object is not an iterator` | `next()` was called on an iterable | Call `iter()` first |
| A second loop or `list()` call yields nothing | The iterator was used up by the first pass | Store results in a list, or create a new iterator |
| Items skipped while editing a list in a loop | The list iterator's index no longer matches the list | Loop over a copy, or build a new list |
| `RuntimeError: dictionary changed size during iteration` | Keys were added or removed during the loop | Loop over `list(d)` or build a new dictionary |
Summary
A for loop calls iter() once on the object after in. It then calls next() on the result until StopIteration is raised. Iterables, such as lists and strings, can hand out new iterators whenever asked. Iterators hold a position, move only forward, and can be consumed once. The functions enumerate and zip take iterables and return iterators, so everything in this chapter applies to their results.
Exercise
A learner writes data = iter([1, 2, 3]), then runs print(sum(data)) followed by print(sum(data)). What do the two lines print, and why?
Show answer
The first line prints 6 and the second prints 0. The sum function consumes the iterator completely on the first call. The second call receives an iterator with no values left, so it adds nothing and returns the starting value 0. No error is raised.
Exercise
What does this code print? it = iter("abcd") next(it) for ch in it: print(ch) break print(next(it))
Show answer
It prints b and then c. The bare next(it) consumes "a" and discards it. The loop receives "b", prints it, and breaks, leaving the iterator after "b". The final next(it) returns "c".
Exercise
Why does for n in numbers: numbers.remove(n) on [1, 2, 3, 4] leave items in the list, and what is a safe way to empty a list while visiting each item?
Show answer
The list iterator stores an index. Each remove shifts the later items left, so the next index skips one item. After this loop the list is [2, 4]. To visit every item safely, loop over a copy (for n in numbers[:]:) or build a new list. To simply empty the list, call numbers.clear() after the loop.
Exercise
Given result = zip([1, 2], [3, 4]), how can you check without consuming it that result is an iterator and not a list?
Show answer
Run iter(result) is result, which is True for an iterator. You can also use isinstance(result, collections.abc.Iterator), or print type(result).__name__, which shows zip. A list would give False for the identity test, because iter() on a list returns a new object.