Skip to the solution
MediumDSA12 min read

What are generators and why use them?

498 views

The problem

Question presented to candidate: "What is a generator in Python, how is it different from a normal function that returns a list, and when would you actually choose one? Give me a case where it matters."

What a strong answer should cover:

  • A function containing yield is a generator function: calling it runs none of the body and returns a generator object; each next() runs the body up to the next yield, hands out that value and pauses with all local state kept
  • A generator is an iterator (it has __iter__ returning itself and __next__), so for, list(), sum() and itertools accept it; it ends with StopIteration when the function returns
  • Lazy evaluation: values are produced only when asked for, so memory stays constant regardless of input size, the first result arrives immediately, work stops when the consumer stops (any(), break, islice), and infinite sequences become possible
  • Generators replace a hand-written iterator class (no __next__, no position bookkeeping) and compose into streaming pipelines (read, filter, transform) where each item flows through every stage before the next is read
  • Trade-offs: single pass, no len() or indexing, errors surface when consumed, and for small data a list can be just as fast or faster
  • Generator expressions (x for x in ...) are the one-line form; yield from, send() and coroutines build on the same machinery

Code / implementation expected: Yes β€” a small generator function, ideally an infinite one cut with itertools.islice, or a two-stage pipeline.

  • generators

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythonyield pausing a function, infinite sequences and a lazy pipeline
PythonGenerator vs iterator class, memory measured, and the single-pass trade-off

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 85 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How does Python's name and object reference model work?

Continue