Combine lazy iteration, bounded consumption and safe resource management.
What You Will Learn
This checkpoint tests whether you understand what an iterator retains, what it consumes, and when a stream should close. Build a pipeline that selects records one at a time, then computes a result. If a source is a file, keep its context manager active during iteration. Avoid unlimited materialization of unbounded iterators.
Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from itertools import islice
def squares():
number = 1
while True:
yield number * number
number += 1
first_five = list(islice(squares(), 5))
print(first_five)
print(sum(first_five))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: itertools.
- The function squares defines reusable behavior; its body executes when it is called, not when it is declared.
- The variable first_five holds the result of list(islice(squares(), 5)). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
[1, 4, 9, 16, 25]
55
When You Would Use This
This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.
Practice: Modify the Code
Build a finite iterator of even numbers, then take only its first three values.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Calling list(squares()) on a generator that never finishes.
- Using a generator after the file handle it depends on was closed.
Key Takeaways
- Combine lazy iteration, bounded consumption and safe resource management.
- This checkpoint tests whether you understand what an iterator retains, what it consumes, and when a stream should close.
- Apply this operation only after checking the assumptions and input conditions shown in the example.