Autocoder

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.

Level1 to 4 years
FocusIterator protocol, yield, lazy evaluation
VersionPython 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. 1

    What is the difference between an iterable and an iterator?

    easy

    An 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.

    python
    it = iter([10, 20])
    print(next(it), next(it))   # 10 20
    next(it)                    # StopIteration
  2. 2

    How does a for loop work under the hood?

    medium

    Python 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().

    python
    items = [1, 2, 3]
    it = iter(items)
    while True:
        try:
            x = next(it)
        except StopIteration:
            break
        print(x)
  3. 3

    What is a generator, and how does it differ from a normal function?

    easy

    A 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.

    python
    def countdown(n):
        while n > 0:
            yield n
            n -= 1
    
    g = countdown(3)
    print(next(g), list(g))   # 3 [2, 1]
  4. 4

    Predict the output: iterating a generator twice.

    medium

    A 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.

    python
    g = (x * x for x in range(3))
    print(list(g))   # [0, 1, 4]
    print(list(g))   # []
    print(sum(g))    # 0
  5. 5

    What is the difference between yield and return?

    medium

    return 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. 6

    Write a generator for Fibonacci numbers and take the first ten.

    medium

    An 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.

    python
    from 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. 7

    What are send(), throw() and close() on a generator?

    hard

    A 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.

    python
    def 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.0
  8. 8

    What does yield from do?

    hard

    yield 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.

    python
    def 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. 9

    How would you read a very large file without loading it into memory?

    medium

    Iterate 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.

    python
    def 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. 10

    How do you write your own iterator class?

    medium

    Implement __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.

    python
    class 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. 11

    List the useful functions in itertools you should know.

    medium

    count, 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.

    python
    from 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. 12

    Predict the output: generator expressions evaluate the first iterable eagerly.

    hard

    In 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.

    python
    data = [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. 13

    Why do generators save memory, and when are lists better?

    medium

    A 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.

    python
    import 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

See all in this section