Python Generators and Iterators Interview Questions
Last updated 2026-11-19
Generators and iterators sit at the heart of how Python loops work, so interview questions here probe whether you understand what a for loop actually does. Expect to explain the iterator protocol, write a generator function, and predict what happens when a generator is consumed twice.
The answers below move from definitions to the harder material: send(), yield from, generator-based pipelines for large files and the exhaustion behaviour that catches many candidates out.
| Level | 1 to 4 years |
|---|---|
| Focus | Iterator protocol, yield, lazy evaluation |
| Version | Python 3.8 and later |
What the interviewer wants to hear
Three phrases signal real understanding: lazy evaluation, constant memory, and single-use. A generator produces values on demand, holds only its current state rather than the whole sequence, and cannot be rewound once exhausted.
Be ready to rewrite a list-building function as a generator, and to say when the list version is actually better.
Where this fits
Generators build on functions and closures from the main Python page, and they pair naturally with decorators and the standard itertools module. For round-by-round advice, see how to crack a Python interview.
Python Generators and Iterators Interview Questions: questions with worked answers
1 What is the difference between an iterable and an iterator?
easyAn iterable is any object with __iter__ that returns an iterator, or with __getitem__ for sequence-style access: lists, strings, dicts, files. An iterator is the object that does the work: it has __next__, which returns the next value or raises StopIteration, and an __iter__ that returns itself. Iterables can be looped many times because each loop asks for a fresh iterator. Iterators are consumed.
pythonit = iter([10, 20]) print(next(it), next(it)) # 10 20 next(it) # StopIteration2 How does a for loop work under the hood?
mediumPython calls iter() on the object to get an iterator, then repeatedly calls next() on it, running the body each time, until StopIteration is raised, which the loop catches silently. This explains why any object implementing the protocol works in loops, comprehensions, unpacking, sum() and list().
pythonitems = [1, 2, 3] it = iter(items) while True: try: x = next(it) except StopIteration: break print(x)3 What is a generator, and how does it differ from a normal function?
easyA generator function contains yield. Calling it does not run the body; it returns a generator object. Each next() runs the body until the next yield, hands back that value and freezes the local state. When the body ends, StopIteration is raised. It uses O(1) memory regardless of how many values it produces, unlike a function that builds and returns a full list.
pythondef countdown(n): while n > 0: yield n n -= 1 g = countdown(3) print(next(g), list(g)) # 3 [2, 1]4 Predict the output: iterating a generator twice.
mediumA generator is an iterator, so once it is exhausted it stays empty. The second loop produces nothing and raises no error. To reuse values, call the generator function again, store results in a list, or use itertools.tee, which buffers values and so costs memory.
pythong = (x * x for x in range(3)) print(list(g)) # [0, 1, 4] print(list(g)) # [] print(sum(g)) # 05 What is the difference between yield and return?
mediumreturn ends the function and discards its state. yield suspends the function, keeps the local variables and the position, and resumes at the same spot on the next next() call. A generator may contain return, which ends the iteration, with any returned value stored in StopIteration.value. A function that contains yield anywhere is a generator, even if the yield is never reached.
6 Write a generator for Fibonacci numbers and take the first ten.
mediumAn infinite generator is safe because values are produced lazily. Use itertools.islice to take a finite slice. The state is just two integers, so memory stays constant.
pythonfrom itertools import islice def fib(): a, b = 0, 1 while True: yield a a, b = b, a + b print(list(islice(fib(), 10))) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]7 What are send(), throw() and close() on a generator?
hardA generator can receive data. gen.send(v) resumes it and makes the paused yield expression evaluate to v. The first call must be send(None) or next() to start it. throw(exc) raises an exception at the paused yield, and close() raises GeneratorExit there so cleanup in finally blocks runs. This is the mechanism behind coroutine-style code before async syntax.
pythondef averager(): total, n, avg = 0, 0, None while True: x = yield avg total += x; n += 1 avg = total / n g = averager() next(g) print(g.send(10), g.send(20)) # 10.0 15.08 What does yield from do?
hardyield from sub delegates to another iterable or generator. It forwards the values the sub-generator yields, forwards send() and throw() to it, and evaluates to the sub-generator's return value. It replaces a for loop that re-yields items and is useful for flattening recursive structures.
pythondef flatten(x): for item in x: if isinstance(item, list): yield from flatten(item) else: yield item print(list(flatten([1, [2, [3, 4]], 5]))) # [1, 2, 3, 4, 5]9 How would you read a very large file without loading it into memory?
mediumIterate over the file object, which is an iterator that yields one line at a time and buffers internally. For fixed-size chunks use iter(callable, sentinel). Wrap the logic in a generator to build a pipeline in which each stage is lazy, so memory stays flat whatever the file size.
pythondef error_lines(path): with open(path, encoding="utf-8") as f: for line in f: if "ERROR" in line: yield line.rstrip() # for line in error_lines("app.log"): ...10 How do you write your own iterator class?
mediumImplement __iter__ returning self and __next__ returning the next item or raising StopIteration. Keep the state on the instance. Because it returns self, the object can be looped once. If you want a reusable iterable, make __iter__ return a fresh iterator, or write __iter__ as a generator method.
pythonclass Count: def __init__(self, n): self.i, self.n = 0, n def __iter__(self): return self def __next__(self): if self.i >= self.n: raise StopIteration self.i += 1 return self.i print(list(Count(3))) # [1, 2, 3]11 List the useful functions in itertools you should know.
mediumcount, cycle and repeat produce infinite streams. islice slices any iterator. chain joins iterables. product, permutations and combinations enumerate combinatorial sets. groupby groups consecutive equal keys and therefore needs sorted input. accumulate gives running totals. zip_longest pads shorter inputs. All return lazy iterators.
pythonfrom itertools import chain, combinations, groupby, accumulate print(list(chain([1], [2, 3]))) # [1, 2, 3] print(list(combinations("abc", 2))) # [('a','b'), ('a','c'), ('b','c')] print(list(accumulate([1, 2, 3, 4]))) # [1, 3, 6, 10] print([(k, len(list(g))) for k, g in groupby("aabbbc")]) # [('a',2),('b',3),('c',1)]12 Predict the output: generator expressions evaluate the first iterable eagerly.
hardIn a generator expression the outermost iterable is evaluated immediately when the expression is created, but everything else is evaluated lazily. So changing the list afterwards does not affect which list is iterated if you rebind the name, but mutating the same list does show up because items are read on demand.
pythondata = [1, 2, 3] g = (x for x in data) data.append(4) # same list object, seen by g print(list(g)) # [1, 2, 3, 4] data = [1, 2, 3] g = (x for x in data) data = [9] # rebinding: g keeps the old list print(list(g)) # [1, 2, 3]13 Why do generators save memory, and when are lists better?
mediumA generator holds one value and a frame, so memory is constant, while a list holds all n values. Lists are better when you need random access, len(), several passes, slicing or when the data is small enough that the overhead of resuming a frame outweighs the saving. A common rule: use a generator for pipelines that are consumed once, and a list when the result is reused.
pythonimport sys print(sys.getsizeof([i for i in range(10**6)]) > 8_000_000) # True print(sys.getsizeof((i for i in range(10**6))) < 300) # True
Frequently asked questions
Can a generator be reused?
No. Once it raises StopIteration it is exhausted. Call the generator function again to get a new one, or keep the values in a list.
Is a list an iterator?
No, it is an iterable. iter(list) returns a separate list iterator object. That is why you can loop over a list many times.
What is StopIteration used for?
It is the signal that an iterator has no more values. Loops catch it automatically. Raising it inside a generator body is converted to RuntimeError since Python 3.7.
What is the difference between a generator and a coroutine?
A generator mainly produces values. Using send() on a generator turns it into a simple coroutine that also consumes values. Modern asynchronous code uses async def and await instead.
Related guides
More in Programming Language Interview Questions by Language
- Python Interview Questions and Answers
- Python Lambda, Map, Filter and Reduce Interview Questions
- Python List, Dict and Set Interview Questions
- Python Memory Management Interview Questions
- Python Multithreading and Multiprocessing Interview Questions
- Python OOPs Interview Questions
- Python String Interview Questions
- SQL CTE and Recursive Query Interview Questions
- SQL GROUP BY and HAVING Interview Questions
- SQL Indexes Interview Questions
- SQL Interview Questions and Answers
- SQL Interview Questions for Freshers