Iteration is fundamental to data processing. And when scanning datasets that don't fit in memory, we need a way to fetch the items lazily, that is, one at a time and on demand. This is what the Iterator pattern is about.
Every generator is an iterator: generators fully implement the iterator interface. But an iterator retrieves items from a collection, while a generator can produce items "out of thin air".
Every collection in Python is iterable, and iterators are used internally to support:
- for loop
- Collection types construction and extension
- Looping over text files line by line
- List, dict, and set comprehensions
- Tuple unpacking
- Unpacking actual parameters with * in function calls
We'll get started studying how the iter(...) function makes sequence iterable.
1. Sentence Take #1: A Sequence of Words.
end ...