Practice Bank: Generators, Iterators & Context Managers
A deeper set of practice problems, organized by topic, for extra reps
beyond the main exercises — including scenario-based problems
written in the same style you'll meet in real interviews. This is the
chapter where yield/generator functions, generator
expressions, and the context-manager protocol
(__enter__/__exit__) become allowed, on top
of everything from Chapters 1-16 (including general classes,
__init__, dunder methods,
@staticmethod/@classmethod/@property,
inheritance, super(), method overriding, polymorphism, and
isinstance()). No import beyond
math/datetime/random/csv.
starter.py below and run
python3 starter.py from inside the same folder.
Topic 1: Iterables vs. Iterators
1 A manual countdown iterator
Find # TODO 1.1. Write a Countdown class with __iter__/__next__ that counts down from a starting value to 0, raising StopIteration after.
2 A separate iterable and iterator
Find # TODO 1.2. Write a RepeatTwice iterable and a matching iterator class that yields each item in a list twice in a row.
3 Driving iter()/next() by hand
Find # TODO 1.3. Manually drive iter()/next() on a list without a for loop, catching StopIteration yourself.
4 A custom even-numbers iterator
Find # TODO 1.4. Write an EvenNumbers class with __iter__/__next__ that produces every even number up to a limit.
5 Debug the Code
Find # TODO 1.5. This __next__ method never raises StopIteration, which would loop forever. Fix it.
A paginated API client walking pages by hand
Find # TODO 1.A. Write a PageWalker iterator that walks through a list of pages one at a time via the iterator protocol.
Iterable vs. iterator
Find # TODO 1.B. Write explain_iterable_vs_iterator(), explaining what makes an object "iterable" versus an "iterator," and how a for loop uses that distinction.
Topic 2: Generator Functions
1 Counting up with yield
Find # TODO 2.1. Write a generator function count_up_to(limit) using yield to produce integers one at a time.
2 Squares, produced lazily
Find # TODO 2.2. Write a generator function squares_up_to(limit) using yield to produce squares.
3 Branching logic inside a generator
Find # TODO 2.3. Write a generator function alternating_signs(limit) mixing if/else logic with yield.
4 Multiple yields of different values
Find # TODO 2.4. Write a generator function countdown_then_liftoff(start) that yields numbers, then a final string.
5 Debug the Code
Find # TODO 2.5. This function was meant to be a generator but used return instead of yield inside its loop. Fix it.
Streaming sensor readings one at a time
Find # TODO 2.A. Write a generator function that lazily filters sensor readings above a threshold.
yield vs. return
Find # TODO 2.B. Write explain_yield_vs_return(), explaining the difference between a function using return and a generator function using yield.
Topic 3: Generator Expressions
1 List comprehension vs. generator expression
Find # TODO 3.1. Compare a list comprehension and a generator expression built from the same source, checking their types.
2 Summing directly over a generator expression
Find # TODO 3.2. Sum values directly over a generator expression with sum().
3 Finding a max lazily
Find # TODO 3.3. Find the max of a generator expression with max().
4 Short-circuiting with any()
Find # TODO 3.4. Use any() over a generator expression to short-circuit on the first match.
5 Debug the Code
Find # TODO 3.5. Square brackets were used where parentheses were meant, turning a lazy generator expression into an eager list comprehension. Fix it.
Checking a huge log file for one matching line without loading it all
Find # TODO 3.A. Use any() with a generator expression to check for a matching line.
Why choose a generator expression?
Find # TODO 3.B. Write explain_genexpr_memory_benefit(), explaining why you'd choose a generator expression over a list comprehension.
Topic 4: The with Protocol Generalized
1 A general-purpose managed resource
Find # TODO 4.1. Write a ManagedResource class with __enter__/__exit__ and use it in a with block, showing state before/after.
2 Guaranteed cleanup on block exit
Find # TODO 4.2. Write a Timer class showing __exit__ runs automatically when the block ends.
3 The exact order of execution
Find # TODO 4.3. Write a NoisyBlock class showing the exact order __enter__/block-body/__exit__ run.
4 Suppressing an exception
Find # TODO 4.4. Write a SuppressValueError class whose __exit__ suppresses a ValueError by returning True.
5 Debug the Code
Find # TODO 4.5. This class is missing __exit__ entirely, so with raises TypeError. Fix it.
Guaranteeing a lock is always released
Find # TODO 4.A. Write a SimpleLock context manager guaranteeing release, even if the code inside raises.
What problem does with solve?
Find # TODO 4.B. Write explain_with_protocol_purpose(), explaining what problem the with statement and context-manager protocol solve.
Topic 5: Writing a Custom Context Manager Class
1 Your first custom context manager
Find # TODO 5.1. Write your first fully custom context manager, LoggingContext, from scratch.
2 Tracking entries across reuse
Find # TODO 5.2. Write a CallCounter context manager tracking how many times it's been entered.
3 Collecting errors instead of crashing
Find # TODO 5.3. Write an ExceptionLogger context manager that collects errors instead of crashing.
4 Modeling commit-on-success
Find # TODO 5.4. Write a Transaction context manager that tracks whether it committed successfully.
5 Debug the Code
Find # TODO 5.5. This __exit__ accidentally returns True, silently swallowing exceptions it shouldn't. Fix it.
A reusable timing context manager for performance checks
Find # TODO 5.A. Write a StepTracker context manager counting completed steps.
The context-manager lifecycle, step by step
Find # TODO 5.B. Write explain_context_manager_lifecycle(), explaining exactly what Python does when it executes a with SomeClass() as x: block.
Topic 6: Bringing It Together — Real-World Use
1 Streaming lines lazily
Find # TODO 6.1. Write a generator function stream_lines(text) that lazily yields lines from text, one at a time.
2 A generator and a context manager together
Find # TODO 6.2. Combine a generator function with a custom context manager to count long lines as they're filtered.
3 Lazily stopping after N matches
Find # TODO 6.3. Write first_n_matching(items, predicate_threshold, limit), a generator that lazily stops after N matches.
4 A simulated file combining both protocols
Find # TODO 6.4. Write a FileSimulator context manager with a lines() generator method, standing in for a real file.
5 Debug the Code
Find # TODO 6.5. This generator function used return with a list comprehension instead of yield, defeating laziness. Fix it.
A log-processing pipeline combining everything
Find # TODO 6.A. Combine a context manager and a generator function to filter error lines from a simulated log.
Where these three tools show up together
Find # TODO 6.B. Write explain_bringing_together(), describing a real production system where generators, iterators, and context managers all show up together.
solution.py. Your exact
wording doesn't need to match — the goal is that your program
runs without errors and does what each TODO asks.