Sub topic 1
Iterables and Iterators: What Is the Difference?
Python programmers say "iterable" and "iterator" as if they were the same word, but they name two different roles. Most of what follows in this tutorial depends on the difference, including how for loops work, how generators behave, and why some loops silently produce nothing the second time. This chapter separates the two roles using only iter() and next(). The next chapter covers the protocol methods behind them.
Prerequisites
This chapter assumes you already know:
- Basic Python syntax: functions, classes, and loops.
- The built-in collections: lists, tuples, dicts, sets, and strings.
- How exceptions and
try/exceptwork. - What a method is, and that special (dunder) methods such as
__len__exist and are called by the language rather than by you.
You do not need to have written a class that supports iteration. That comes later.
Two roles, two definitions
- An iterable is an object that can hand out its items one at a time. You can ask it for an iterator. Lists, tuples, strings, dicts, sets, and ranges are iterables.
- An iterator is an object that produces the items. It remembers where it is and returns the next item each time you ask. When no items remain, it signals the end.
An iterable is something you can loop over. An iterator is the thing doing the walking. An iterable is like a book, and an iterator is a bookmark moving through it. You can put many bookmarks in one book, and each keeps its own place.
Using iter() and next()
Two built-in functions connect the roles:
iter(obj)asks an iterable for an iterator.next(it)asks an iterator for its next item.
numbers = [10, 20]
it = iter(numbers)
print(next(it)) # 10
print(next(it)) # 20
try:
next(it)
except StopIteration:
print("exhausted")The list numbers never changes. The call iter(numbers) creates a separate object, it, that tracks a position in the list. After two calls to next(), the position is at the end. A third call raises StopIteration, the exception that means "no more items". Python uses an exception here instead of a special return value, because any value, including None, could be a legitimate item.
An iterable gives out a fresh iterator each time
Every call to iter() on a list returns a new iterator with its own position:
numbers = [1, 2, 3]
a = iter(numbers)
b = iter(numbers)
print(next(a), next(a)) # 1 2
print(next(b)) # 1
print(a is b) # FalseIterator b starts at the beginning even though a has already moved. This is why you can loop over the same list many times and why two nested loops over one list do not interfere with each other. The state lives in the iterators, not in the list.
Iterators are also iterable
An iterator is itself an iterable, and asking it for an iterator returns the same object:
numbers = [1, 2, 3]
it = iter(numbers)
print(iter(it) is it) # True
print(next(it)) # 1
for value in it: # continues from where it left off
print(value) # 2, then 3This rule lets a for loop accept either kind of object. A loop calls iter() on whatever you give it. For a list it gets a new iterator. For an iterator it gets that same iterator, so the loop continues from the current position instead of starting over.
The relationship is one-directional:
- Every iterator is an iterable.
- Not every iterable is an iterator. A list is not one.
Comparing the roles
| Question | Iterable | Iterator |
|---|---|---|
| What does it do? | Provides an iterator on request | Produces items one at a time |
| Does it track a position? | No | Yes |
| What does `iter(x)` return? | A new iterator each time | Itself |
| Does `next(x)` work? | No, raises `TypeError` | Yes |
| Can you loop over it twice? | Usually yes | No, it is exhausted after one pass |
| Examples | `list`, `tuple`, `str`, `dict`, `set`, `range` | `iter([1])`, `map(...)`, `zip(...)`, generators, open files |
Which built-ins are which
Some common cases surprise people. range is an iterable, not an iterator. map, zip, and enumerate return iterators, not lists. Open file objects are iterators.
You can check with the abstract base classes in collections.abc:
from collections.abc import Iterable, Iterator
samples = {
"list": [1, 2],
"str": "ab",
"range": range(3),
"list_iterator": iter([1, 2]),
"map": map(str, [1, 2]),
"generator": (x for x in range(2)),
}
for name, obj in samples.items():
print(name, isinstance(obj, Iterable), isinstance(obj, Iterator))
# list True False
# str True False
# range True False
# list_iterator True True
# map True True
# generator True TrueEvery row is iterable. Only the last three are also iterators. A practical consequence follows from this:
r = range(3)
print(list(r)) # [0, 1, 2]
print(list(r)) # [0, 1, 2] (a range gives a fresh iterator each time)
m = map(str, [1, 2])
print(list(m)) # ['1', '2']
print(list(m)) # [] (the map is its own iterator and is now exhausted)The range can be consumed repeatedly because each list(r) obtains a new iterator. The map object is the iterator, so the second call finds it already at the end. The pitfalls chapter returns to this.
How the two roles relate
Why Python separates the two roles
If a list were its own iterator, it would need a "current position" field. Nested loops over one list would then fight over that position, and any loop that finished would leave the list unusable. Separating the roles puts the state in a small, disposable object and keeps the collection itself unchanged.
The split also lets objects that have no storage at all take part in loops. A network stream, a file being read, or a generator computing values on demand has no list of items to hand out. It can only be an iterator. Those objects get one pass, and the iterator protocol makes that explicit.
Edge cases and common errors
Calling next() on an iterable
next() works only on iterators. Passing a list is a common mistake:
try:
next([1, 2, 3])
except TypeError as e:
print(e) # 'list' object is not an iterator
try:
iter(5)
except TypeError as e:
print(e) # 'int' object is not iterableThe fix for the first error is next(iter(my_list)). The second error means the object offers no way to produce an iterator, so you cannot loop over it.
Iterating a dict gives keys
iter(d) on a dictionary walks the keys. Use d.values() or d.items() to get the other views. Each of those is also an iterable that hands out a fresh iterator.
Changing a collection while iterating
An iterator reads the live collection, not a snapshot. Adding or removing keys from a dict during iteration raises RuntimeError: dictionary changed size during iteration. Removing items from a list while looping over it does not raise an error. It silently skips elements, because the iterator's position index no longer matches the shifted items. Loop over a copy (list(items)) or build a new collection instead.
Exhaustion is permanent
After an iterator raises StopIteration, it keeps raising it. Python does not rewind it. To traverse the data again, go back to the original iterable and call iter() again.
Old-style iterables
An object that defines __getitem__ with integer indexes starting at 0 but no __iter__ still works with iter() and for. Python falls back to an older sequence protocol. Such objects pass iter(obj) but fail isinstance(obj, Iterable). The reliable test for "can I loop over this?" is to call iter(obj) and catch TypeError.
Summary
- An iterable can be asked for an iterator with
iter(). - An iterator returns items with
next(), remembers its position, and raisesStopIterationat the end. - An iterator returns itself from
iter(), so it is also an iterable. - Collections such as lists and ranges are iterables only, so you can loop over them repeatedly. Objects such as
map,zip, generators, and files are iterators, so you get one pass.
Exercise
Given data = [5, 6, 7], it = iter(data), and the calls next(it), next(it), then list(it), what does the final list(it) return, and what does list(data) return afterwards?
Show answer
list(it) returns [7], because the iterator has already consumed 5 and 6 and continues from its current position. list(data) returns [5, 6, 7], because the list is an iterable that holds no position, and it hands out a fresh iterator from the start.
Exercise
Why does the second list(m) return [] in m = map(str, [1, 2]); list(m); list(m), while the second list(r) still returns all items in r = range(3)?
Show answer
A map object is an iterator. iter(m) returns m itself, so the first list(m) exhausts it and the second finds nothing left. A range is only an iterable. Each list(r) calls iter(r), which creates a new iterator that starts at the beginning.
Exercise
What error do you get from next("abc"), and how do you change the code so it returns "a"?
Show answer
It raises TypeError: 'str' object is not an iterator, because a string is an iterable but not an iterator. Write next(iter("abc")) to get an iterator first, which returns "a".