Iterable and Iterator Protocol
Scenario: A for loop somehow knows how to walk lists, files, ranges, and custom objects.
New words, in plain English
- Iterable - an object
iter()can ask for an iterator - Iterator - an object
next()asks for one value at a time - StopIteration - the signal that no values remain
- Lazy - computed only when requested
A for loop calls iter, repeatedly calls next, then stops on StopIteration. Iterators are consumed; create a fresh one to start over.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
values = iter([10, 20])
print(next(values))
print(next(values))
# next(values) would now raise StopIteration
Tip: Most code should use for; knowing the protocol explains why it works.
Goal: Practice this idea in the py-generators challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.