Interview Q&A · Python · 20 questions in this topic
Iterators & Generators — Python Interview Q&A
The iterator protocol, yield, lazy evaluation and the memory arguments that decide between a generator and a list. Part of Iterators & Generators · 375 questions in the Python bank.
What is an iterable, and how is it different from an iterator?
Answer
An iterable is any object you can loop over (it implements __iter__, which returns an iterator). An iterator is the object that actually does the iterating — it implements __next__ and remembers its current position, produced by calling iter() on an iterable.
Every iterator is also an iterable (its __iter__ typically returns itself), but not every iterable is an iterator — a list is iterable but is not itself an iterator, since it doesn't track position; calling iter() on it produces a separate list-iterator object that does.
Example
nums = [1, 2, 3] # iterable -- has __iter__ print(hasattr(nums, "__iter__")) # True print(hasattr(nums, "__next__")) # False -- list itself is NOT an iterator it = iter(nums) # calling iter() produces an iterator print(hasattr(it, "__next__")) # True print(next(it)) # 1 print(next(it)) # 2
💡 The one-sentence distinction to nail: "an iterable knows how to produce an iterator; an iterator knows how to produce the next value and remembers where it left off." Most confusion comes from treating the two as synonyms.
What does the iter() function do?
Answer
iter(obj) returns an iterator for obj by calling its __iter__ method internally. It's what a for loop calls automatically, once, before it starts repeatedly calling next().
iter() also supports a lesser-known two-argument form, iter(callable, sentinel), which repeatedly calls callable() until it returns a value equal to sentinel — a pattern occasionally used for reading fixedsize chunks or polling until a stop condition.
Example
nums = [10, 20, 30] it = iter(nums) print(type(it)) # <class 'list_iterator'> # The two-argument "sentinel" form import random random.seed(1) def roll(): return random.randint(1, 6) for value in iter(roll, 6): # keeps rolling until it gets a 6 print(value)
💡 Mentioning the two-argument iter(callable, sentinel) form is a nice "hidden gem" detail — most developers only ever use the single-argument version.
What does next() do, and what happens when an iterator is exhausted?
Answer
next(iterator) retrieves the next value from an iterator by calling its __next__ method. Once there are no more values, the iterator raises StopIteration — which is exactly the signal a for loop relies on internally to know when to stop.
next() accepts an optional second argument as a default value to return instead of raising StopIteration, which is useful when you want to consume "one more item, or a fallback" without wrapping the call in a try / except.
Example
it = iter([1, 2]) print(next(it)) # 1 print(next(it)) # 2 # print(next(it)) # StopIteration! print(next(it, "no more items")) # "no more items" -- default avoids the exception
💡 Point out that a for loop is essentially syntactic sugar for repeatedly calling next() inside a try / except StopIteration: block — this connects the abstract protocol to the everyday syntax everyone already uses.
What is the iterator protocol?
Answer
The iterator protocol is the pair of dunder methods an object must implement to be a proper iterator: __iter__ (returning itself) and __next__ (returning the next value, or raising StopIteration when exhausted).
Implementing this exact protocol is what makes a custom object compatible with for loops, list(), sum(), unpacking, and every other construct in Python that consumes iterables — it's a small, consistent contract that unlocks broad language-level support.
Example
class CountUpTo: def __init__(self, limit): self.limit = limit self.current = 0 def __iter__(self): return self # an iterator's __iter__ returns itself def __next__(self): if self.current >= self.limit: raise StopIteration self.current += 1 return self.current for n in CountUpTo(3): # works seamlessly in a for loop print(n) # 1 2 3
💡 Being able to write this exact CountUpTo pattern from memory — including remembering that __iter__ on an iterator just returns self — is one of the most commonly requested live-coding micro-exercises in Python interviews.
How would you implement a custom iterable class (as opposed to a custom iterator)?
Answer
Implement __iter__ to return a fresh iterator object each time it's called, rather than returning self — this allows multiple independent iterations over the same object at once, unlike a plain iterator which gets consumed after one pass.
This is a subtle but important distinction from Q134: a class that is only an iterator (returns self from __iter__) can only be looped over once — once exhausted, it stays exhausted. A class designed to be re-iterated multiple times (like a list) should instead return a new iterator object on each call to __iter__.
Example
class NumberRange: # iterable, not itself an iterator def __init__(self, limit): self.limit = limit def __iter__(self): return NumberRangeIterator(self.limit) # fresh iterator every time class NumberRangeIterator: def __init__(self, limit): self.limit = limit self.current = 0 def __iter__(self): return self def __next__(self): if self.current >= self.limit: raise StopIteration self.current += 1 return self.current numbers = NumberRange(3) print(list(numbers)) # [1, 2, 3] print(list(numbers)) # [1, 2, 3] -- works again! independent iterator each time
What are generators in Python?
Answer
A generator is a special kind of function that produces a sequence of values lazily, one at a time, using yield instead of return. Calling a generator function doesn't run its body immediately — it returns a generator object that produces values on demand.
Generators automatically implement the entire iterator protocol for you (__iter__ and __next__) — you get all the benefits of a custom iterator class from Q134/135 without writing any of that boilerplate yourself.
Example
def count_up_to(limit): current = 1 while current <= limit: yield current # pauses here, returns current, resumes on next() current += 1 gen = count_up_to(3) print(type(gen)) # <class 'generator'> print(next(gen)) # 1 print(next(gen)) # 2 print(list(count_up_to(3))) # [1, 2, 3] -- consuming a fresh generator fully
💡 "A generator function automatically implements the iterator protocol for you" is the key insight — it directly connects this question back to the manual CountUpTo class from Q134, showing generators as a massive shortcut for the same underlying mechanism.
What is the yield keyword, and how does it differ from return?
Answer
yield pauses a function's execution, sends a value back to the caller, and preserves all local state so execution can resume exactly where it left off on the next call. return exits a function completely and permanently, discarding all its local state.
A function containing even one yield statement anywhere in its body becomes a generator function — calling it never runs any code immediately, it just creates a generator object; the body only starts executing on the first call to next().
Example
def normal_function(): return 1 return 2 # unreachable -- return exits immediately and permanently def generator_function(): yield 1 # pauses here, remembers everything yield 2 # resumes right here on the next next() call yield 3 print(normal_function()) # 1 -- function is already done gen = generator_function() print(next(gen)) # 1 print(next(gen)) # 2 -- picked up exactly where it left off print(next(gen)) # 3
💡 "The presence of yield anywhere in a function body changes the entire function's nature to a generator function" is a detail worth stating explicitly — even a yield inside a conditional branch that never executes still makes the whole function a generator.
How do generator expressions differ from generator functions?
Answer
A generator expression is a concise, one-line way to create a generator using comprehension-like syntax: (x for x in iterable). A generator function is a full def block that uses yield internally. Both produce the same kind of generator object and behave identically once created.
Choose a generator expression for simple, single-transformation cases (analogous to when you'd choose a list comprehension over a loop); choose a full generator function when the logic needs multiple steps, branching, or intermediate state that doesn't fit cleanly into one expression.
Example
# Generator expression -- simple, one-line squares_expr = (n ** 2 for n in range(5)) # Equivalent generator function -- more verbose, but scales to complex logic def squares_func(): for n in range(5): yield n ** 2 print(list(squares_expr)) # [0, 1, 4, 9, 16] print(list(squares_func())) # [0, 1, 4, 9, 16] -- identical result
💡 This mirrors the list comprehension vs. loop trade-off exactly — reach for the expression form for simple cases, and a full generator function once you need multiple steps or conditional logic that doesn't fit in one line.
What is the difference between a generator and a list?
Answer
A list stores all of its elements in memory at once and can be iterated over repeatedly, indexed, and sliced. A generator computes and yields one value at a time, uses far less memory for large sequences, but can only be iterated over once and doesn't support indexing.
Key points
- 1Memory usage — List: Stores every element at once; Generator: Only the current state — negligible
- 2Can iterate multiple times? — List: Yes; Generator: No — exhausted after one pass
- 3Indexing/slicing (x[i]) — List: Yes; Generator: No
- 4Evaluation — List: Eager (computed immediately); Generator: Lazy (computed on demand)
- 5Best for — List: Small/medium data, repeated access; Generator: Large/streaming data, single pass
Example
gen = (n for n in range(3)) print(list(gen)) # [0, 1, 2] print(list(gen)) # [] -- already exhausted, second pass gets nothing lst = [n for n in range(3)] print(lst) # [0, 1, 2] print(lst) # [0, 1, 2] -- lists can be "iterated" (read) repeatedly
💡 "A generator is exhausted after one full iteration, a list is not" is the single most likely follow-up trap if you claim generators and lists are interchangeable — always caveat that trade-off unprompted.
What is lazy evaluation, and why does it matter for generators?
Answer
Lazy evaluation means a value isn't computed until it's actually needed. Generators are lazy by nature — creating one does no work at all; each value is computed only when next() is called, which is what makes them memoryefficient for large or even infinite sequences.
This is the opposite of "eager" evaluation (like a list comprehension), which computes and stores every value immediately. Lazy evaluation is what makes it possible to represent conceptually infinite sequences in Python without ever running out of memory, as long as you never try to fully materialize them into a list.
Example
def infinite_counter(): n = 0 while True: # infinite loop -- would crash a list comprehension instantly yield n n += 1 counter = infinite_counter() # creating it does NO work at all print(next(counter)) # 0 -- computed only now print(next(counter)) # 1 -- computed only now # list(infinite_counter()) # would hang/crash -- eager evaluation can't handle infinite sequences
💡 The "infinite sequence" example is the cleanest possible demonstration of why lazy evaluation matters — it's something a list comprehension or a fully eager approach genuinely cannot do at all, not just "does less efficiently."
Can you iterate over the same generator more than once?
Answer
No. Once a generator is exhausted (its StopIteration has been raised), it stays exhausted permanently — iterating over it again yields nothing. If you need to iterate multiple times, you must create a new generator by calling the generator function (or expression) again.
This is a direct consequence of a generator being both an iterable and an iterator simultaneously (its __iter__ returns self) — there's no separate, resettable "iterable" object backing it the way a list has, so there's nothing to restart from the beginning.
Example
def gen_func(): yield 1 yield 2 yield 3 g = gen_func() print(list(g)) # [1, 2, 3] print(list(g)) # [] -- exhausted, nothing left # Correct approach: create a fresh generator for each pass print(list(gen_func())) # [1, 2, 3] -- new generator, works fine print(list(gen_func())) # [1, 2, 3] -- another new one, also works fine
What state does a generator preserve between yield calls?
Answer
A generator preserves its entire local execution state between yield calls: all local variables, the exact point of execution (the paused line), and the state of any loops or try/except blocks it's currently inside.
This is what makes generators fundamentally different from a normal function call, which starts fresh with a new local scope every time. A generator's frame is suspended, not destroyed, and Python keeps it alive in memory until the generator is exhausted or garbage collected.
Example
def running_total(): total = 0 # this variable persists across every yield while True: value = yield total # pauses here; value captures what is sent in via send() total += value gen = running_total() next(gen) # "primes" the generator, advances to the first yield -> returns 0 print(gen.send(10)) # total becomes 10, yields 10 print(gen.send(5)) # total becomes 15, yields 15 print(gen.send(100)) # total becomes 115, yields 115
💡 This "running total" example is a great one to have ready — it demonstrates persisted local state (total) and previews the send() mechanism from Q143 in one cohesive demonstration.
What does send() do in a generator?
Answer
generator.send(value) resumes a paused generator, sends value in to become the result of the current yield expression, and runs until the next yield (or the generator ends), returning that next yielded value.
This turns a generator from a one-way value producer into a two-way communication channel — the caller can push data into the generator's execution, not just pull values out. A generator must already be "primed" (advanced once via next()) before the first send() with an actual value, since there's no yield expression waiting to receive a value until execution has reached one.
Example
def echo(): while True: received = yield print(f"Received: {received}") e = echo() next(e) # prime the generator -- advances to the first yield e.send("hello") # Received: hello e.send("world") # Received: world
What does throw() do in a generator?
Answer
generator.throw(exception_type) raises the given exception at the point where the generator is currently paused (inside its yield expression), letting the generator's own try / except logic handle it, or letting it propagate out if unhandled.
This is mainly useful for cleanly injecting cancellation or error conditions into a generator-based coroutine or pipeline from the outside, giving the generator a chance to clean up (via finally or a try / except) before terminating.
Example
def resilient_generator(): try: while True: yield "running" except ValueError: print("Caught ValueError inside the generator, cleaning up") yield "recovered" g = resilient_generator() print(next(g)) # 'running' print(g.throw(ValueError)) # prints "Caught ValueError..." then yields 'recovered'
💡 This is a genuinely advanced, less commonly known feature — even mentioning it correctly (without needing deep mastery) signals broader familiarity with the generator protocol beyond the basics.
What does close() do in a generator?
Answer
generator.close() raises a GeneratorExit exception at the generator's current suspension point, which typically causes it to stop (via an unhandled GeneratorExit, which is allowed to propagate) — useful for explicitly signaling that you're done consuming a generator and want it to release any resources.
If the generator has a finally block wrapping its yield, that cleanup code will run when close() is called, exactly like closing any other resource — making generators a viable (if less common) way to model resource lifecycles alongside context managers.
Example
def resource_generator(): print("Resource acquired") try: yield "using resource" finally: print("Resource released") # guaranteed cleanup, even on close() gen = resource_generator() print(next(gen)) # "Resource acquired" then "using resource" gen.close() # triggers the finally block -> "Resource released"
💡 Mention that a generator is also automatically closed (and its finally cleanup runs) when it's garbage collected, even if close() is never called explicitly — though relying on garbage collection timing for cleanup carries the same caveats as __del__, Q110).
What is yield from, and when would you use it?
Answer
yield from iterable delegates iteration to another iterable or generator, yielding each of its values in turn — it's a concise way to flatten nested generators or compose several generators into one, without writing an explicit inner loop.
Beyond just saving a loop, yield from also correctly forwards send(), throw(), and close() calls down into the sub-generator, and captures its return value — behavior that a naive manual for. yield loop does not replicate.
Example
def inner(): yield 1 yield 2 def outer(): yield "start" yield from inner() # equivalent to: for x in inner(): yield x yield "end" print(list(outer())) # ['start', 1, 2, 'end'] # Useful for flattening nested generators recursively def flatten(nested): for item in nested: if isinstance(item, list): yield from flatten(item) # delegate recursively else: yield item print(list(flatten([1, [2, 3, [4, 5]], 6]))) # [1, 2, 3, 4, 5, 6]
💡 The recursive flatten() example is a favorite live-coding exercise — practice writing it from memory, since it combines yield from, recursion, and isinstance() checks in one compact, testable function.
How do generators help with memory efficiency when processing large files?
Answer
Instead of reading an entire file into memory as a list of lines, you can process it line-by-line (or chunk-by-chunk) using a generator, keeping memory usage constant regardless of the file's total size.
This is one of the most practical, frequently tested applications of everything covered in this section — file objects in Python are already iterators over their lines, so simply looping over an open file directly is memory-efficient by default; the anti-pattern to avoid is calling.readlines(), which defeats this by loading everything at once.
Example
# Memory-heavy: loads the ENTIRE file into a list before processing anything def count_errors_bad(path): with open(path) as f: lines = f.readlines() # entire file in memory at once return sum(1 for line in lines if "ERROR" in line) # Memory-efficient: processes one line at a time, constant memory usage def count_errors_good(path): with open(path) as f: return sum(1 for line in f if "ERROR" in line) # f is already a lazy iterator # A custom generator for chunked (not line-based) reading of huge files def read_in_chunks(path, chunk_size=8192): with open(path, "rb") as f: while chunk := f.read(chunk_size): yield chunk
💡 If asked "how would you process a 10 GB file," the expected answer is exactly this: iterate lineby-line (or in fixed-size chunks) using the file object's natural laziness, never call.readlines() or.read() on the whole file at once.
What is the relationship between StopIteration and how for loops end?
Answer
StopIteration is the specific exception an iterator raises from __next__ to signal "there are no more values." A for loop catches this exception internally and simply exits the loop cleanly — it isn't treated as a program error at all when it comes from normal iteration.
This means StopIteration is a completely normal, expected part of Python's iteration machinery, not an error condition — you only need to worry about it directly if you're calling next() manually rather than using a for loop, which handles the exception for you automatically.
Example
def manual_for_loop(iterable): it = iter(iterable) while True: try: value = next(it) except StopIteration: break # exactly what a real 'for' loop does internally print(value) manual_for_loop([10, 20, 30]) # prints 10, 20, 30, then stops cleanly
💡 Note that since Python 3.7 (PEP 479), a StopIteration raised accidentally inside a generator's body (not from normal exhaustion) is converted into a RuntimeError instead — this was a deliberate change to prevent a StopIteration bug from silently truncating a yield from chain or a for loop that consumes the generator.
Can a generator function have a return statement? What does it do?
Answer
Yes. return value inside a generator function stops the generator (raising StopIteration internally, as always) and attaches value to that StopIteration 's.value attribute — retrievable directly when using yield from, though not when iterating with a plain for loop.
A bare return (no value) inside a generator is equivalent to simply reaching the end of the function body — both just stop the generator normally. return value, however, is specifically how a generator can communicate a "final result" distinct from all the values it yielded along the way.
Example
def countdown_with_result(): yield 3 yield 2 yield 1 return "Liftoff!" # attached to StopIteration, not a normally yielded value gen = countdown_with_result() print(list(gen)) # [3, 2, 1] -- the return value is NOT included here # Accessing the return value requires yield from, or manual StopIteration handling: def wrapper(): result = yield from countdown_with_result() print(f"Got result: {result}") # 'Liftoff!' list(wrapper()) # triggers the print as a side effect
💡 The distinction "the return value is attached to StopIteration, not yielded as a normal value" is subtle and frequently missed — showing the yield from retrieval pattern demonstrates real hands-on familiarity with this corner of the language.
What are some common real-world use cases for generators?
Answer
Generators shine anywhere you're processing large or unbounded data streams: reading huge files line-by-line, paginating through an API's results, building data processing pipelines, producing infinite sequences, and implementing custom, memory-efficient iteration logic for your own classes.
A particularly powerful pattern is chaining multiple generators together into a lazy processing pipeline — each stage only pulls the next item from the previous stage when it's actually needed, so the entire pipeline processes one item at a time end-to-end instead of materializing intermediate full-sized lists.
Example
def read_lines(path): with open(path) as f: for line in f: yield line.strip() def filter_errors(lines): for line in lines: if "ERROR" in line: yield line def extract_timestamps(lines): for line in lines: yield line.split(" ")[0] # A lazy pipeline: nothing is read from disk until the final list()/for loop pulls values through pipeline = extract_timestamps(filter_errors(read_lines("app.log"))) # for timestamp in pipeline: ... # processes the file one line at a time, end to end
💡 This "pipeline of generators" pattern is an excellent answer to "how would you process a huge log file to extract specific data" — it demonstrates composing several of this section's concepts (laziness, yield, single-pass iteration) into one coherent, realistic design.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission