# Generators & Iterators

> What are generators in Python? How are they different from regular functions and from building a list?

Canonical: https://www.internhack.in/learn/interview/python-interview/python-generators
Last updated: 2026-11-28

Difficulty: Advanced

## Question

What are generators in Python? How are they different from regular functions and from building a list?

## Answer

A generator is a function that contains `yield`. Calling it does not run the body; it returns a generator object that produces values lazily, one per `next()` call, pausing at each `yield` and resuming exactly where it left off. Because only one value exists at a time, a generator can process a 10 GB log file or an infinite stream in constant memory, where a list would have to hold everything at once.

### The iterator protocol underneath

Every `for` loop in Python uses two methods:

- `iter(obj)` calls `obj.__iter__()` and returns an iterator.
- `next(it)` calls `it.__next__()` and returns the next value, or raises `StopIteration` when done.

Writing an iterator class by hand means managing state in attributes and raising `StopIteration` yourself. A generator function gives you all of that for free: Python saves the local variables and the instruction pointer in the generator's frame between calls. A generator is both an iterable and its own iterator, which is why it can be consumed **only once**.

### Generator vs regular function vs list

| Aspect | Regular function returning a list | Generator |
| --- | --- | --- |
| When work happens | All at once, before returning | On demand, per `next()` |
| Memory | O(n), whole list in RAM | O(1) for the generator state |
| Reuse | Iterate as many times as you like | Exhausted after one pass |
| Indexing, `len()` | Supported | Not supported |
| Infinite sequences | Impossible | Natural |

Use a list when you need random access, multiple passes or `len()`. Use a generator when you stream data once: reading files, paging through an API, or chaining transformations.

### yield, generator expressions and yield from

- **Generator expression**: `(x * x for x in nums)` is the lazy cousin of a list comprehension. `sum(x * x for x in nums)` never builds the list.
- **yield from**: `yield from sub_gen()` delegates to another iterable and forwards values, `send()` and exceptions. It is the clean way to flatten nested generators.
- **send() and close()**: generators can receive values with `gen.send(v)` (the `yield` expression evaluates to `v`). This was the basis of old-style coroutines before `async`/`await`, and it still powers `contextlib.contextmanager`.
- **return in a generator**: the returned value is attached to the `StopIteration` and becomes the result of `yield from`.

### Pipelines in real systems

Generators shine as stages in a pipeline, the same idea as Unix pipes. A Swiggy order-analytics job might read lines from a file, parse JSON, filter failed orders and sum amounts in paise, with each stage a generator. Nothing is materialised in between, so memory stays flat no matter how big the input is. Django's `QuerySet.iterator()`, `csv.reader`, `os.walk` and file objects all expose this lazy style.

### Gotchas interviewers probe

- **Exhaustion**: `g = (x for x in range(3)); list(g); list(g)` gives `[0, 1, 2]` and then `[]`.
- **Late errors**: since nothing runs until iteration, an exception in the body appears at the first `next()`, not at the call.
- **StopIteration inside a generator**: since Python 3.7 (PEP 479), a `StopIteration` that leaks out of a generator body is converted to `RuntimeError`. Use `return` to finish.
- **Resource cleanup**: a generator holding an open file only closes it when exhausted or garbage-collected. Wrap the `open()` in `with` inside the generator, and call `close()` if you abandon it early.

**How a for loop drives a generator. The generator runs only until the next yield, then hands control back to the caller.**

1. for loop → Generator: next(): start running body
2. Generator → for loop: yield 1 and pause
3. for loop → Generator: next(): resume after yield
4. Generator → for loop: yield 2 and pause
5. for loop → Generator: next(): resume again
6. Generator → for loop: body ends, StopIteration

## Code examples

### Generator function vs list version

```
import sys

def squares_list(n):
    return [i * i for i in range(n)]

def squares_gen(n):
    for i in range(n):
        yield i * i          # pause here, resume on next()

lst = squares_list(1_000_000)
gen = squares_gen(1_000_000)
print(sys.getsizeof(lst) > 8_000_000)   # list holds a million pointers
print(sys.getsizeof(gen) < 500)         # generator holds only its frame

g = squares_gen(3)
print(next(g), next(g), next(g))
print(list(g))   # already exhausted
```

The list stores every element up front; the generator stores only its paused state. Once consumed, a generator yields nothing more.

### Lazy pipeline over a large log file

```
import json

def read_lines(path):
    with open(path, encoding="utf-8") as f:   # closed when generator finishes
        yield from f

def parse(lines):
    for line in lines:
        yield json.loads(line)

def failed_orders(records):
    return (r for r in records if r["status"] == "FAILED")

def total_paise(path):
    records = parse(read_lines(path))
    return sum(r["amount_paise"] for r in failed_orders(records))

# Works the same for 10 lines or 10 crore lines: one record in memory at a time.
# print(total_paise("orders.jsonl"))
```

Each stage pulls one item at a time from the previous stage, so memory use stays constant regardless of file size.

## Key points

- Calling a generator function returns a generator object; the body runs on next()
- Generators are single-pass iterators; materialise with list() if you need reuse
- Generator expressions use parentheses and avoid building intermediate lists
- yield from delegates to a sub-iterator and forwards send() and exceptions
- Since Python 3.7, StopIteration raised inside a generator becomes RuntimeError

## Common follow-up questions

- How would you write the same thing as an iterator class with \__iter_\_ and \__next_\_?
- What does gen.send() do and where is it used today?
- What is the difference between yield and yield from?
- How do async generators (async def with yield) differ?
- How would you read a 20 GB CSV file without running out of memory?

## Interview tips

- Lead with memory: O(1) state vs O(n) list, then give the large-file example
- Show you know generators are single-use; it is the gotcha most candidates miss
- Linking generators to the iterator protocol (\__iter_\_/\__next_\_/StopIteration) signals depth

## Concepts covered

Generators, yield, Iterator Protocol, Lazy Evaluation, yield from, Generator Expressions

Previous: [Decorators & Metaprogramming](https://www.internhack.in/learn/interview/python-interview/python-decorators) · Next: [GIL & Concurrency](https://www.internhack.in/learn/interview/python-interview/python-gil) · [All of Python Interview](https://www.internhack.in/learn/interview/python-interview)

## More Python Interview questions

- [Variables & Data Types](https://www.internhack.in/learn/interview/python-interview/python-variables-types)
- [Strings & String Methods](https://www.internhack.in/learn/interview/python-interview/python-strings)
- [Lists, Tuples & Sets](https://www.internhack.in/learn/interview/python-interview/python-lists-tuples-sets)
- [Dictionaries & Operations](https://www.internhack.in/learn/interview/python-interview/python-dictionaries)
- [Control Flow & Loops](https://www.internhack.in/learn/interview/python-interview/python-control-flow)
- [Functions & Arguments](https://www.internhack.in/learn/interview/python-interview/python-functions)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Python Interview](https://www.internhack.in/learn/interview/python-interview)
