Interview Questions: Generators, Iterators & Context Managers
Generators, iterators, and context managers are where interviews test whether you actually understand what's happening under the hood, not just whether you can write a for loop. This set covers the real difference between an iterable and an iterator, what happens internally when next() hits an exhausted iterator, why a generator beats building a full list in memory, the concrete "10GB log file" scenario interviewers love to ask, generator functions vs. generator expressions, what with actually guarantees and why that matters even when exceptions happen, how to write a custom context manager class, and one of the most genuinely common gotchas: what __exit__ returning True does differently from returning None or False.
1 What's the actual difference between an "iterable" and an "iterator"? Aren't they the same thing?
They're related but distinct, and the distinction is one of the most commonly tested points on this topic. An iterable is anything you can call iter() on to get an iterator back — it defines __iter__. A list, a string, a dict, a set: all iterables. An iterator is the object that actually does the stepping — it defines __next__ (and typically also its own __iter__ that returns itself), and it remembers exactly where it is between calls. A list is iterable, but a list itself is not an iterator: it has no __next__ method, and calling next([1, 2, 3]) raises a TypeError. What a for loop actually does under the hood is call iter() on the iterable to get a fresh iterator, then repeatedly call next() on that iterator until it raises StopIteration. So every iterator is iterable (it can be passed to iter(), which just returns itself), but not every iterable is an iterator — the iterable is the "container" that knows how to produce an iterator, and the iterator is the thing that actually tracks position and produces values one at a time.
Treating "iterable" and "iterator" as interchangeable words for the same thing, or not being able to say which one defines __next__.
"Does numbers = [1, 2, 3]; next(numbers) work?" (No — it raises TypeError: 'list' object is not an iterator, because a list is iterable but isn't itself an iterator; you'd need it = iter(numbers) first, and then next(it) works.)
2 What actually happens internally when a for loop runs over a list?
A for loop is syntactic sugar over the iterator protocol, not some special magic separate from it. Concretely, for x in some_list: is roughly equivalent to: call it = iter(some_list) once to get an iterator, then repeatedly call next(it), assigning each returned value to x and running the loop body, until next(it) raises StopIteration — at which point the loop catches that exception internally and simply ends, with no error visible to the code that wrote the for loop. This is exactly why custom classes that define both __iter__ and __next__ can be looped over with a plain for loop with zero special-casing: Python doesn't know or care that the object is a custom class, it just follows the same protocol it would follow for a list or a string.
Describing for loops as fundamentally different from the iterator protocol, or not knowing that StopIteration is what silently ends the loop rather than something the loop body ever sees.
"If a custom class defines __iter__ and __next__ correctly, does for item in my_object: need any special support from Python beyond that?" (No — that's the entire point of the protocol; any object implementing it correctly works with a plain for loop, list(...), tuple unpacking, and anything else that iterates, with no extra code needed anywhere.)
3 What actually happens when you call next() on an iterator that's already exhausted?
It raises StopIteration — every single time, not just once. Once an iterator has produced its last value and been asked for one more, it stays permanently exhausted: calling next() on it again doesn't restart it or wrap around, it just raises StopIteration again and again forever. This is a genuinely common point of confusion, especially for anyone assuming an iterator is like a list that can be "re-looped." If you need to iterate the same sequence of values again, you need a brand-new iterator — for a list, that means calling iter() on it again (a fresh iterator starts at the beginning); for a generator, the exhausted generator object itself cannot be reset at all, and the generator function has to be called again to produce a new generator object from scratch.
Assuming an exhausted iterator "resets" or wraps around, or not knowing that a generator specifically can never be un-exhausted — a new call to the generator function is required.
Follow-up"If g = my_generator_function() gets fully exhausted, can calling next(g) again ever produce a value?" (No — once exhausted, a generator object is done permanently; every further next(g) call raises StopIteration, and getting new values requires calling my_generator_function() again to get a fresh generator object.)
4 What's the actual difference between yield and return inside a function?
return exits a function immediately and permanently, handing back one final value (or none) — once a function returns, its local state is gone. yield instead pauses the function, hands back one value to whoever called next(), and — crucially — remembers exactly where it left off, including every local variable's value, so the next call to next() resumes execution right after that yield line rather than starting the function over. A function containing even one yield anywhere in its body automatically becomes a generator function: calling it doesn't run any of its code immediately at all, it just returns a generator object, and the function's actual code only starts running the first time next() is called on that generator. This is fundamentally different from a normal function, where calling it runs the whole body (until a return or the end) immediately and gives back one final value.
Thinking calling a generator function runs its code immediately, or believing yield exits the function permanently the same way return does.
"Given def f(): yield 1; yield 2, does calling f() print anything or run any code by itself?" (No — calling f() just creates and returns a generator object; none of the function's code runs until next() is called on it for the first time.)
5 Why use a generator instead of just building and returning a full list?
Memory and laziness. A function that builds a full list has to hold every single value in memory at once before it can return anything — for a million items, that's a million items sitting in RAM simultaneously, whether or not the caller ever actually needs all of them. A generator instead produces values lazily, one at a time, only computing the next value the moment something actually asks for it via next() — at any given point, a generator only needs to remember its current position and local state, not every value it has produced or will ever produce. This matters enormously for large or even infinite sequences: a generator can represent "all the natural numbers" or "every line of a 10GB file" without ever trying to hold the whole thing in memory, because it never builds "the whole thing" as a data structure at all — it just knows how to produce the next value when asked.
Saying generators are "just faster" without mentioning memory, or not being able to explain what "lazy" actually means in terms of when computation happens.
Follow-up"Could a function using return [x for x in range(10_000_000_000)] ever actually finish running?" (No, realistically — it would try to build and hold ten billion integers in memory at once, exhausting available RAM long before it finished; a generator that yields each value one at a time, or a generator expression doing the same, never needs to hold more than the current value in memory.)
6 You need to process a 10GB log file, line by line, counting how many lines mention "ERROR." What's wrong with reading the whole file into a list first?
Something like lines = file.readlines() loads the entire 10GB file into memory as a list of strings before a single line gets processed — on most machines, that alone is enough to exhaust available RAM and crash the program, or at minimum slow the whole machine to a crawl through swapping, long before the actual counting logic even starts. The fix is to never materialize the whole file as a data structure at all: iterate the file object directly, since an open file object is itself an iterator that yields one line at a time — for line in file: ... — or wrap that in a generator function that yields only the lines matching "ERROR," so at any given moment the program only holds the current line in memory, not all ten million lines of the file. The total memory footprint stays roughly constant (one line's worth) regardless of whether the file is 10 megabytes or 10 gigabytes, because nothing ever needs to hold "the whole file" as one object.
Suggesting file.read() or file.readlines() as the starting point without flagging the memory problem, or not knowing that an open file object can be iterated directly line-by-line without any manual line-splitting.
"Does for line in open('huge_file.txt'): ever hold the whole file in memory at once?" (No — a file object is its own iterator; each iteration reads and yields just the next line from disk, so memory use stays roughly constant no matter how large the file is.)
7 What's the difference between a generator function and a generator expression? When would you reach for one over the other?
Both produce a generator object with the same laziness benefits, but they look and are written completely differently. A generator function is a regular def whose body contains one or more yield statements — it's the right tool when the logic producing each value needs multiple lines, branching, loops, or state beyond a single expression (e.g. reading a file and applying several conditions per line). A generator expression is a single-expression, parenthesized shorthand that looks almost identical to a list comprehension but with () instead of [] — (x * x for x in range(10)) instead of [x * x for x in range(10)] — and is the right tool when the whole transformation fits naturally as one expression over one iterable, exactly the situations where a list comprehension would otherwise be reached for. The key shared benefit over a list comprehension: [x * x for x in range(10_000_000)] builds the entire list in memory immediately, while (x * x for x in range(10_000_000)) builds nothing yet at all — it just creates a generator object that computes each squared value lazily as something iterates over it.
Confusing a generator expression's parentheses with a tuple (a common trap — (x for x in range(5)) is a generator, not a "tuple comprehension," because Python has no such thing), or not knowing when the extra structure of a full generator function is actually needed.
"Is (x for x in range(5)) a tuple?" (No — parentheses around a comprehension-like expression make a generator expression, not a tuple; Python has no "tuple comprehension" syntax at all, which is exactly why this particular parenthesized form means something different from what it might look like at first glance.)
8 What does the with statement actually guarantee, and why does that matter even when an exception happens inside it?
with guarantees that a resource's cleanup code runs no matter how the block exits — whether it finishes normally, returns early, or raises an exception partway through. Concretely, with open("file.txt") as f: ... guarantees f.close() runs even if the code inside the block raises an exception on line one of the block, which a plain f = open(...); ... ; f.close() sequence does not guarantee — if an exception is raised between the open() and the manual close() call, that close() line simply never executes, and the file handle leaks. This matters a great deal for real resource management: file handles, network connections, and database connections are all limited system resources, and a program that leaks them on every exception path will eventually run out, often in production under exactly the error conditions that were hardest to test for. with moves cleanup out of "hope the code path reaches it" territory and makes it unconditional.
Believing manual close() calls are just as safe as with as long as they're written at the end of the code, without accounting for exceptions raised before that line is reached.
"If code inside with open('data.txt') as f: raises a ValueError on its very first line, does f still get closed?" (Yes — that's precisely the guarantee with provides; the file's cleanup runs as the exception propagates out of the block, before the exception continues upward, regardless of where inside the block it was raised.)
9 What are __enter__ and __exit__, and how do they connect to the with statement?
They're the two dunder methods that make an object usable with with — together they're called the "context manager protocol." When Python evaluates with some_object as x:, it calls some_object.__enter__() first, and whatever that method returns gets assigned to x (often self, but not required to be). Then the block's code runs. When the block finishes — normally or via an exception — Python calls some_object.__exit__(exc_type, exc_value, traceback), passing information about any exception that occurred (all three arguments are None if the block finished normally with no exception). __exit__ is where cleanup logic belongs: closing a file, releasing a lock, closing a connection — it runs unconditionally once the block is done, which is exactly what gives with its cleanup guarantee.
Not knowing __exit__ receives exception information as arguments, or thinking __enter__'s return value is always just self with no other option.
"If the code inside a with block raises no exception at all, what values does __exit__ receive for exc_type, exc_value, and traceback?" (All three are None — __exit__ is still called every time the block ends, but when there was no exception, Python simply has nothing to report and passes None for all three.)
10 How would you write your own custom context manager as a class? Walk through a concrete example.
Define a class with both __enter__(self) and __exit__(self, exc_type, exc_value, traceback). For example, a simple timer context manager: __enter__ records the current time (e.g. via time.perf_counter()) onto self and returns self, so with Timer() as t: gives access to the timer object inside the block; __exit__ records the end time, computes the elapsed duration, and prints or stores it — and since __exit__ always runs regardless of how the block ended, the elapsed time gets reported even if the code inside the block raised an exception partway through. The class doesn't need to inherit from anything special or import anything beyond what the cleanup logic itself needs (like the time module for a timer) — defining those two specific methods is the entire contract that makes an object work with with.
Forgetting that __exit__ needs to accept the three exception-info parameters even if it doesn't use them, or thinking a context manager class needs some special base class or decorator to work with with.
"If a custom context manager's __exit__ is defined as def __exit__(self, exc_type, exc_value, traceback): but the body only ever prints a completion message and never touches those three parameters, is that valid?" (Yes — the parameters have to be accepted since Python always passes them, but a context manager is free to ignore them entirely if it has no exception-specific behavior to run; simply not reading them doesn't affect the protocol at all.)
11 This is a genuinely common one: what does __exit__ returning True do differently from returning None or False?
It controls whether an exception raised inside the with block gets suppressed or allowed to continue propagating. If __exit__ returns a truthy value (most explicitly True), Python treats the exception as handled and swallows it — code after the with block continues running normally, as if nothing went wrong, even though something inside the block genuinely raised an exception. If __exit__ returns None or any falsy value (which is what happens by default if __exit__ doesn't explicitly return anything at all, since a function with no explicit return returns None), the exception continues propagating normally after __exit__ finishes running, exactly as if the with block weren't there. This is genuinely dangerous to get wrong: a context manager that returns True from __exit__ without a very deliberate reason silently hides real bugs and errors from the rest of the program, since the exception simply vanishes instead of surfacing anywhere.
Not knowing that returning True suppresses the exception entirely, or treating exception suppression as a default/harmless behavior rather than something that should be deliberate and rare.
"If __exit__ returns True after a ValueError was raised inside the with block, does code immediately after the with block still run?" (Yes — returning True tells Python the exception was handled, so it's suppressed entirely and execution continues normally right after the block, with no exception visible to anything outside it.)
12 Can a generator function be used as a context manager, or do those require entirely separate approaches?
They're built on genuinely separate protocols — a generator function on its own is not automatically usable with with. A generator function defines __next__-driven lazy iteration (built around yield); a context manager needs __enter__/__exit__ instead, which is an entirely different pair of dunder methods with a different calling contract. Python's standard library does offer a bridge (contextlib.contextmanager, using a single yield to separate setup code from teardown code) that lets a generator-shaped function be turned into a context manager — but that's a decorator doing real translation work between the two protocols, not the two protocols being secretly the same thing. Writing a context manager directly as a class with explicit __enter__/__exit__ methods (as this chapter does) is the more fundamental approach and doesn't rely on any additional standard-library helper at all.
Assuming any function containing yield automatically works with with, or being unable to name what's actually different between the iterator protocol and the context manager protocol.
"Does a plain generator function like def gen(): yield 1 work directly in with gen() as g:?" (No — a generator object has __iter__/__next__, not __enter__/__exit__, so using it directly in a with statement raises an AttributeError; it would need to be wrapped by something like contextlib.contextmanager to work with with at all.)
13 Why does an open file object work directly in a for loop without calling any special method to "get its lines" first?
Because a file object, once opened, already is an iterator over its own lines — it implements __iter__ (returning itself) and __next__ (returning the next line each time it's called, raising StopIteration once the file is exhausted). This is exactly why for line in file_object: works with no extra method call needed: the for loop just follows the ordinary iterator protocol, and the file object already satisfies it. This is also precisely why file iteration is memory-efficient by default — each call to __next__ reads and returns just the next line from disk, rather than the file object having pre-loaded every line into memory the moment it was opened.
Assuming a file object needs .readlines() called first before it can be looped over, or not connecting file iteration back to the same iterator protocol used everywhere else.
"Does for line in open('data.txt'): load the whole file into memory before the loop starts?" (No — the file object is its own iterator and reads one line at a time as __next__ gets called, so it never holds more than the current line's worth of data in memory regardless of the file's total size.)
14 A custom context manager's __enter__ raises an exception before it finishes. Does __exit__ still get called?
No — and this is a genuinely important edge case. Python only calls __exit__ if __enter__ completed successfully and the with block was actually entered. If __enter__ itself raises an exception, the with statement never considers the block "opened" in the first place, so there's no corresponding __exit__ call to balance it — the exception from __enter__ just propagates upward as if the whole with statement had failed on its very first line. This means any resource acquisition that could partially succeed before failing needs to be handled carefully inside __enter__ itself (e.g. cleaning up any partial state before re-raising), since __exit__ won't automatically be given a chance to help.
Assuming __exit__ always runs no matter what, including when __enter__ itself is the thing that failed.
"If a context manager's __enter__ opens a file successfully but then raises an exception on its next line before returning, is that file handle guaranteed to be closed by __exit__?" (No — since __exit__ is never called in this case, whoever writes __enter__ needs to close that file handle manually inside __enter__'s own error handling before re-raising, or the handle leaks.)
Rapid-Fire Review
Quick recall check — fill in each blank and hit Check.