Sub topic 1
Iterables, Iterators and the Iteration Protocol
Prerequisites
You should know Python functions, loops, comprehensions, lists, tuples, and basic generators. Familiarity with yield and lambda is useful but not required.
Iterables and iterators
An iterable is an object that can provide its items one at a time. Lists, strings, dictionaries, and files are iterable. An iterator is the object that remembers its current position and produces the next item.
Python uses two operations:
iter(value)obtains an iterator from an iterable.next(iterator)requests the next item.- When no items remain,
nextraisesStopIteration.
A for loop performs this protocol automatically.
numbers = [10, 20, 30]
items = iter(numbers)
print(next(items))
print(next(items))
print(list(items))This prints 10, 20, and [30]. The iterator has already consumed the first two values.
An iterable can usually create multiple independent iterators. An iterator itself is normally single-use.
it = map(str, range(3))
print(list(it))
print(list(it))The output is:
['0', '1', '2']
[]Why lazy iteration saves memory
Lazy evaluation means producing a value only when it is requested. An iterator does not need to store its entire result. This is useful for large files, database results, and streams.
flowchart TD
A[Source iterable] --> B[Lazy iterator]
B --> C[next request]
C --> D[One value]
D --> CInfinite streams with `count`, `cycle` and `repeat`
The itertools module provides iterators that do not end:
count(start, step)produces an arithmetic sequence.cycle(iterable)repeats an iterable forever.repeat(value)produces the same value forever, or a fixed number of times when giventimes.
Never consume an unbounded iterator without a stopping condition.
Taking slices with `islice`
islice applies start, stop, and step positions to any iterator. Unlike normal list slicing, it does not require a sequence or copy the selected values first.
from itertools import count, islice
timestamps = count(10, 5)
print(list(islice(timestamps, 4)))The output is [10, 15, 20, 25]. The infinite iterator is safe here because islice requests only four values.
Exercise
Why does list(it) return an empty list the second time for an iterator?
Show answer
The first call consumes every remaining item, so the iterator has reached its end.