Python · Functional Python

Iterators & Generators: Practice Questions

100 questions. Try each one yourself before checking the answer.

Short on time? Filter by Must Do for the 25 questions that cover this topic on their own.

Q1iter() & next()EasyMust Do

Turn a list into an iterator with iter() and pull values from it one at a time with next().

Q2StopIterationEasyMust Do

Show what happens when an iterator runs out.

Q3iter() & next()Easy

Use next() with a default so exhaustion returns a value instead of raising.

Q4IterablesEasy

Show that lists, strings, tuples, sets, dictionaries and ranges are all iterable.

Q5The for LoopEasyMust Do

Rewrite a for loop using only iter(), next() and while, to show what for does underneath.

Q6ExhaustionEasy

Show that an iterator can only be walked once.

Q7ExhaustionEasy

Show that two iterators over the same list keep separate positions.

Q8File IteratorsEasy

Show that a file object is its own iterator — the Topic 12 behaviour, explained.

Q9Iterable vs IteratorEasy

Show the difference between an iterable and an iterator by checking for __iter__ and __next__.

Q10__iter__EasyMust Do

Make your own class iterable in the simplest way: return an iterator from __iter__.

Q11Iterator ProtocolEasyMust Do

Write a full iterator class with __iter__ and __next__.

Q12Iterator ProtocolEasy

Show the difference between an iterator class that can be reused and one that cannot.

Q13yieldEasyMust Do

Write your first generator function using yield.

Q14yieldEasy

Show a generator being used in a for loop and converted to a list.

Q15yieldEasy

Show that a generator pauses and resumes, by printing on both sides of the yield.

Q16Generator vs FunctionEasy

Compare a generator with an ordinary function that builds and returns a list.

Q17Lazy EvaluationEasyMust Do

Prove that a generator only does work when asked.

Q18Infinite GeneratorsEasy

Write a generator with no end and take values from it safely.

Q19Generator ExpressionsEasyMust Do

Write a generator expression and show it is a generator, not a list.

Q20Generator ExpressionsEasy

Use a generator expression directly inside sum(), max() and min().

Q21Generator ExpressionsEasy

Add a condition to a generator expression to filter values.

Q22Generator StateEasy

Show that a generator remembers its local variables between calls.

Q23yield fromEasy

Use yield from to hand off to another iterable.

Q24__iter__ with yieldEasy

Make a class iterable by writing __iter__ as a generator.

Q25Generators & FilesEasy

Write a generator that yields cleaned lines from a file.

Q26GeneratorsMediumMust Do

Write a Fibonacci generator that can produce as many terms as asked for.

Q27GeneratorsMedium

Write a prime number generator and take the first N primes from it.

Q28PipelinesMediumMust Do

Chain three generators into a pipeline where each stage feeds the next.

Q29PipelinesMedium

Build a numeric pipeline and prove only the requested values are computed.

Q30GeneratorsMedium

Write generators that filter and transform, then combine them.

Q31yield fromMediumMust Do

Use yield from recursively to flatten an arbitrarily nested list.

Q32yield fromMedium

Walk a nested dictionary structure with yield from, producing paths to every leaf.

Q33GeneratorsMedium

Write a generator that produces running totals from a stream of numbers.

Q34GeneratorsMedium

Write a sliding-window generator.

Q35GeneratorsMedium

Write a chunking generator that yields fixed-size batches.

Q36GeneratorsMedium

Write a generator that yields only values it has not seen before.

Q37Generator ReturnMedium

Show that a generator can return a value, and how to read it.

Q38Generator ReturnMedium

Capture a generator's return value using yield from.

Q39close()Medium

Use .close() to stop a generator early, and try/finally to clean up.

Q40send()Medium

Use .send() to pass a value back into a paused generator.

Q41itertoolsMediumMust Do

Use itertools.count, islice and takewhile for infinite sequences.

Q42itertoolsMedium

Use itertools.chain, cycle and repeat.

Q43itertoolsMedium

Use itertools.groupby to group consecutive equal items.

Q44MemoryMediumMust Do

Measure the memory difference between a list and a generator.

Q45Generators & FilesMediumMust Do

Write a generator that yields parsed records from a CSV file.

Q46Iterator ProtocolMedium

Write an iterator class that produces values without storing them.

Q47__reversed__Medium

Support reversed() on your own class.

Q48PipelinesMedium

Build a reusable pipeline helper that applies a list of stages.

Q49GeneratorsMedium

Write a generator that merges two already-sorted streams.

Q50Generator ExpressionsMedium

Nest generator expressions and use one inside another.

Q51Real-WorldMediumMust Do

Process a log file as a stream, reporting counts without loading the file.

Q52PipelinesMedium

Build a paginator that yields pages of results from a long sequence.

Q53Real-WorldMediumMust Do

Simulate a sensor producing readings forever, and monitor it until a condition is met.

Q54Generators & FilesMedium

Build a grep-like tool that yields matching lines with their numbers.

Q55Real-WorldMediumMust Do

Stream a large CSV, validating rows and reporting bad ones without stopping.

Q56Real-WorldMedium

Build a moving-average generator for a stream of readings.

Q57Infinite GeneratorsMedium

Build an ID generator that produces unique identifiers on demand.

Q58Real-WorldMedium

Build a retry generator that yields attempt numbers with increasing waits.

Q59yield fromMediumMust Do

Walk a nested folder-like structure with yield from.

Q60Real-WorldMedium

Build a progress-reporting generator that wraps any iterable.

Q61Generators & FilesMedium

Stream two files and report which lines differ, without loading either.

Q62Real-WorldMediumMust Do

Build a word-frequency counter that streams a large text.

Q63GeneratorsMedium

Sample every nth item from a stream, and take a random sample from a stream of unknown length.

Q64Real-WorldMedium

Build a batching processor that sends records to a fake API in groups.

Q65Real-WorldMedium

Build a generator that produces a calendar-like sequence of working days.

Q66itertoolsMedium

Use itertools to build a round-robin task assigner.

Q67PipelinesMedium

Build a data-cleaning pipeline with a report of what each stage removed.

Q68GeneratorsMedium

Build a generator that yields running statistics over a stream.

Q69Real-WorldMedium

Build a generator-based state machine that consumes a stream of events.

Q70Real-WorldMedium

Build a generator that reads records and yields only changes from the previous one.

Q71ExhaustionHardMust Do

This report shows a total of zero. Explain why and give two fixes.

def squares(limit):
    for n in range(1, limit + 1):
        yield n ** 2
 
values = squares(5)
 
print(f"values: {list(values)}")
print(f"total:  {sum(values)}")
print(f"count:  {sum(1 for _ in values)}")
Q72GeneratorsHard

Show the operations that do not work on a generator, and what to use instead.

Q73Lazy EvaluationHard

Explain why this generator expression produces surprising results.

multiplier = 2
doubled = (n * multiplier for n in [1, 2, 3])
 
multiplier = 10
print(list(doubled))
Q74Lazy EvaluationHardMust Do

Show what happens when a generator's source is consumed elsewhere.

Q75GeneratorsHard

Show what happens when a generator is created inside a loop rather than outside it.

Q76StopIterationHard

Show what happens when StopIteration is raised inside a generator.

Q77MemoryHard

Measure the real memory and time difference on a large workload.

Q78Iterable vs IteratorHard

Show the bug caused by returning self from __iter__ when the class holds the position.

Q79Infinite GeneratorsHardMust Do

Show the ways an infinite generator can hang a program, and how to guard against them.

Q80GeneratorsHard

Show that a return inside a generator ends it silently, and how that hides bugs.

Q81GeneratorsHard

Show that modifying a list while a generator walks it causes trouble.

Q82GeneratorsHard

Show what happens to try/finally cleanup when a generator is abandoned rather than exhausted.

Q83Generator ExpressionsHard

Compare a generator expression with the equivalent list operation and say when each wins.

Q84PipelinesHard

Show that a deep pipeline still uses constant memory, and what its real cost is.

Q85DesignHard

Show three cases where reaching for a generator is the wrong choice.

Q86Mini-ProjectMini-ProjectMust Do

Build a Streaming Log Analyser: read, parse, filter and summarise a log file through a generator pipeline that never loads it.

Q87Mini-ProjectMini-Project

Build a CSV Processing Pipeline with composable stages and a summary of what each stage dropped.

Q88Mini-ProjectMini-ProjectMust Do

Build a Number Sequence Toolkit of infinite generators with a shared take helper.

Q89Mini-ProjectMini-Project

Build a Paginated Search over a large dataset that only computes the page requested.

Q90Mini-ProjectMini-Project

Build a Sensor Monitoring System with infinite sensor streams, alerting and a live summary.

Q91Mini-ProjectMini-Project

Build a File Search Tool that streams several files and reports matches with context.

Q92Mini-ProjectMini-Project

Build a Batch Job Runner that streams work, batches it, retries failures and reports.

Q93Mini-ProjectMini-Project

Build a Nested Structure Walker that flattens any depth of nesting and reports on it.

Q94Mini-ProjectMini-Project

Build a Streaming Statistics Engine that reports without ever storing the data.

Q95Mini-ProjectMini-Project

Build a Text Processing Pipeline producing a full report from a streamed document.

Q96InterviewInterview

Explain the difference between an iterable, an iterator and a generator, with code for each.

Q97The for LoopInterview

Explain exactly what a for loop does, and what that means for your own classes.

Q98DesignInterview

Give a clear rule for choosing between a generator and a list, with the trade-offs.

Q99Lazy EvaluationInterview

Explain lazy evaluation: what it means, what it buys, and what it costs.

Q100CapstoneInterviewMust Do

Capstone. Build a Generator Toolkit Report demonstrating the whole topic: the iterator protocol by hand, a class made iterable, generator functions and expressions, yield from, an infinite source, a multi-stage pipeline, itertools, .send(), cleanup with close(), and a memory comparison.

Still stuck on something?

Book a free 1-on-1 session and we'll work through it together.

Book a Free Session