Python Master Course V2 — 101. Iterators and the Iterator Protocol
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · LESSON 101 / 200 · ADVANCED PYTHON
Iterators and the Iterator Protocol
Level: Intermediate to advanced · Study: 90–120 minutes · Prerequisites: loops, functions, classes, collections and exceptions.
Video lesson
Video not yet available. Reserved for a verified video URL/player; the complete written lesson follows.
Learning objectives
- Distinguish iterable objects from iterators.
- Use iter(), next(), StopIteration and for loops correctly.
- Implement __iter__ and __next__ in a custom class.
- Understand one-pass consumption and lazy evaluation.
- Use itertools for efficient iteration and recognize memory/performance tradeoffs.
- Build a paginated data reader with tests.
1. Detailed explanation: iterable versus iterator
An iterable can supply an iterator, typically through __iter__(). Lists, strings and dictionaries are iterable. An iterator tracks iteration state and provides __next__(), which returns the next item or raises StopIteration when exhausted. An iterator normally returns itself from __iter__().
A for loop conceptually obtains an iterator with iter(source), repeatedly calls next(iterator), and stops on StopIteration. Iterators support incremental processing and can avoid loading all data at once. But an iterator is often consumed after one pass, so rerunning a loop on the same iterator may produce no values.
Memory model: a list stores its elements, while a range or generator can produce values as requested. Laziness can reduce memory but may move computation costs to consumption time. It does not guarantee constant memory if you materialize results with list().
Understand and apply: Iterators and the Iterator Protocol
Make exhaustion a reliable contract
An iterator owns a position; an iterable supplies an iterator. Calling iter() twice on a list produces independent positions, while calling iter() on an iterator returns the same position. Consequently, a function that accepts an iterable should consume it only as many times as its contract allows. A preliminary sum(), membership search or conversion to list() can consume data that a later operation expected to see.
A countdown needs an integer domain. Testing only start < 0 admits 0.5, whose repeated subtraction never reaches zero. Reject non-integers before creating iteration state, and decide explicitly that booleans are not counts. Once an iterator raises StopIteration, further calls must continue to signal exhaustion; resetting in __iter__ would break this rule and make nested loops interfere unpredictably.
Python example
class Countdown:
def __init__(self, start):
if type(start) is not int or start < 0:
raise ValueError("start must be a nonnegative integer")
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 = Countdown(2)
assert iter(counter) is counter
print(next(counter), next(counter))
print(next(counter, "done"), next(counter, "done"))
assert list(Countdown(0)) == []
for invalid in (-1, 0.5, True, "3"):
try:
Countdown(invalid)
except ValueError:
pass
else:
raise AssertionError("invalid start was accepted")
print("Boundary checks passed")
Expected output
2 1
done done
Boundary checks passed
Give reusable data fresh traversal state
A reusable collection should retain configuration while returning a new iterator for each traversal. Here CountdownSeries remembers a starting number, and each __iter__ call constructs a separate Countdown. The container is reusable even though every iterator it produces remains one-pass. The explicit loop also shows why returning None is not an exhaustion signal: None could be a legitimate item.
Python example: continue after the Countdown definition
class CountdownSeries:
def __init__(self, start):
Countdown(start) # Validate without consuming anything.
self.start = start
def __iter__(self):
return Countdown(self.start)
series = CountdownSeries(3)
first, second = iter(series), iter(series)
print(next(first), next(second), next(first))
print(list(series), list(series))
Expected output
3 3 2
[3, 2, 1] [3, 2, 1]
The inventory project already holds every page in a Python list. Its item-by-item traversal is lazy, but acquiring the pages is not. To fetch lazily, inject a fetch_page function and call it only after the current page iterator is exhausted. Keep at most the current page, validate its list shape and each record, and distinguish an empty page from an explicit end marker. A page-count cap and repeated-token detection prevent a broken server from creating an endless scan.
Test that creating the iterator makes zero fetch calls, consuming one item fetches only its containing page, empty pages are skipped, malformed records raise the documented error, and exhaustion remains stable. For inventory data, require a nonempty string sku and a nonnegative exact-integer qty. Do not claim complete schema validation when checking only that a dictionary contains a sku key.
2. Progressive runnable examples
Requires Python 3.10+. Run each example independently in a .py file. Expected outputs are supplied for comparison.
Example 1 — iter() and next()
values = [10, 20, 30]
it = iter(values)
print(next(it))
print(next(it))
print(next(it, "finished"))
print(next(it, "finished"))
10
20
30
finished
The optional default argument to next() avoids raising StopIteration when the iterator is exhausted.
Example 2 — Iterables can create fresh iterators
values = [1, 2]
first = iter(values)
second = iter(values)
print(next(first))
print(next(first))
print(next(second))
1
2
1
Both iterators start independently because the list creates new iterator objects.
Example 3 — A one-pass iterator
numbers = iter([2, 4, 6])
print(list(numbers))
print(list(numbers))
[2, 4, 6]
[]
Once exhausted, the iterator cannot be rewound automatically.
Example 4 — Custom countdown iterator
class Countdown:
def __init__(self, start):
if type(start) is not int or start < 0:
raise ValueError("start must be a nonnegative integer")
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current == 0:
raise StopIteration
result = self.current
self.current -= 1
return result
print(list(Countdown(4)))
[4, 3, 2, 1]
This is a stateful iterator. It is not a reusable iterable: once consumed, the same object stays exhausted.
Example 5 — Lazy mapping and filtering
numbers = range(1, 8)
evens = filter(lambda x: x % 2 == 0, numbers)
squares = map(lambda x: x * x, evens)
print(list(squares))
[4, 16, 36]
map() and filter() return iterators. The transformation happens as values are consumed.
Example 6 — itertools.islice
from itertools import count, islice
sequence = count(start=10, step=5)
print(list(islice(sequence, 4)))
[10, 15, 20, 25]
count() is unbounded; always limit consumption of potentially infinite iterators.
3. Guided project — Paginated inventory stream
Scenario: A store exposes inventory records in pages. Build a one-pass iterator over pages already held in a local list. Validate page and record data and stop cleanly. This traversal avoids a second flattened list; it does not fetch pages from a server or bound the memory used by the source pages. No network access or API key is required.
class InventoryPages:
def __init__(self, pages):
if not isinstance(pages, list) or not all(isinstance(page, list) for page in pages):
raise ValueError("pages must be a list of lists")
self.pages = pages
self.page_index = 0
self.item_index = 0
def __iter__(self):
return self
def __next__(self):
while self.page_index < len(self.pages):
page = self.pages[self.page_index]
if self.item_index < len(page):
item = page[self.item_index]
self.item_index += 1
if (not isinstance(item, dict)
or not isinstance(item.get("sku"), str)
or not item["sku"].strip()
or type(item.get("qty")) is not int
or item["qty"] < 0):
raise ValueError("record requires a nonblank sku and nonnegative integer qty")
return item
self.page_index += 1
self.item_index = 0
raise StopIteration
pages = [
[{"sku": "PEN", "qty": 10}, {"sku": "BOOK", "qty": 4}],
[],
[{"sku": "BAG", "qty": 2}],
]
items = InventoryPages(pages)
print([item["sku"] for item in items])
print(list(items))
['PEN', 'BOOK', 'BAG']
[]
Walkthrough: the iterator tracks a page index and an item index. It skips empty pages, validates each record and returns one item per call. When all pages are consumed, it raises StopIteration. A real API client would also need timeouts, bounded retries, authorization, pagination loop detection and schema validation.
Tests: assert that empty pages are skipped; assert that invalid records raise ValueError; assert that repeated consumption returns an empty list; test an empty source and a single-item source.
4. Common mistakes and debugging
- Confusing iterables and iterators: not every iterable is its own iterator.
- Trying to reuse an exhausted iterator.
- Forgetting to raise StopIteration at the end.
- Materializing an unbounded iterator with list().
- Assuming lazy iteration eliminates all memory costs.
- Mutating the underlying collection during iteration without a clear policy.
5. Exercises and model answers
What does next(iter([5, 6])) return?
Answer: 5.
Why is list(iter([1,2])) repeatable only with a fresh iterator?
Answer: each iterator maintains its own consumption state.
Modify Countdown to include zero.
Model: stop when current is below zero, then decrement after returning the current value.
Limit an infinite count() sequence to five values.
Model: list(islice(count(), 5)).
Refactor InventoryPages to expose a fresh iterator on every traversal.
Model: store source pages in a separate iterable and return a new iterator from __iter__.
Practice with explained answers
Predict each result before opening the answer. Trace state changes and explain the contract as well as the output.
What does iter(iterator) do to the current position?
It returns the same iterator without rewinding it. After one value has been consumed, the next call continues at the second value. A collection can instead return a newly created iterator.
Worked answer
values = iter([10, 20])
print(next(values))
print(next(iter(values)))
Expected output
10
20
Why is 0.5 dangerous in the original Countdown?
Its values become 0.5, -0.5, -1.5 and so on, never equal to zero. Materializing that iterator can keep allocating indefinitely. Validate type(start) is int and start >= 0 before iteration; do not demonstrate the bug by calling list() on that input.
How would you include zero while retaining correct exhaustion?
Keep integer validation and stop when current is below zero. Return the current value before decrementing. A start of zero then yields exactly one value, and every subsequent next() raises StopIteration.
Worked answer
def __next__(self):
if self.current < 0:
raise StopIteration
value = self.current
self.current -= 1
return value
Why does CountdownSeries support two complete traversals?
Each call to __iter__ returns a different Countdown object initialized from the stored start. Its mutable current field belongs to that new iterator, so consuming one traversal does not advance another.
Does an empty fetched page necessarily mean the inventory stream has ended?
Only if the source contract says so. An API can return an empty page with a continuation token. Follow that token, enforce a page limit, and stop on the explicit terminal marker. Tests should include an empty middle page followed by data.
What memory claim is accurate for the original InventoryPages project?
It avoids creating a second flattened collection while traversing. All supplied pages already reside in memory, so it does not demonstrate bounded-memory page acquisition. A real lazy fetcher should retain only the current page and a deliberately bounded amount of pagination state.
6. Five-question knowledge check
What does iter(x) normally return? A an iterator; B a string; C a list always; D a boolean.
Answer A. iter() obtains an iterator from an iterable.
What signals exhaustion? A ValueError; B StopIteration; C TypeError; D KeyError.
Answer B. The iterator protocol uses StopIteration.
Which is commonly one-pass? A list; B tuple; C iterator; D dict.
Answer C. Iterators maintain consumption state.
What is dangerous with an infinite iterator? A next(); B islice(); C a bounded for loop; D list() without a limit.
Answer D. Unbounded materialization can exhaust memory.
What should __iter__ return on an iterator? A self; B None; C a string; D a number.
Answer A. Iterators return themselves from __iter__.
7. Mastery checkpoint
Explain iterable versus iterator, implement a custom iterator, demonstrate exhaustion, complete the paginated stream project and add tests for empty, valid and malformed data. This page does not claim synchronized progress tracking or certification.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.