MediumExperience level: 3-5 years · 8-15 years1 min read

What is a generator and how does yield work?

Reviewed by Gurusankar M.

Asked inAmazonGoogleMicrosoftDeloitte
#generator#yield#lazy#memory#iterator
Report issue

Short Answer

A generator is a function that uses `yield` to produce values lazily, one at a time, pausing and resuming its state between calls. It doesn't build the whole result in memory, so it handles huge or infinite streams cheaply. Calling it returns a generator (an iterator) you loop over.

On this page

Concept Made Simple

Coffee Chat Question

“What is a generator and how does yield work?”

Remember It Faster

Mind Map Answer

yield
produce a value, pause, keep state
Lazy
computes on demand, item by item
Memory
O(1) — no full list built
Genexpr
(x for x in xs) - inline generator

Learn by Doing

Hands-on Keyboard

python
def first_n(n):
    i = 0
    while i < n:
        yield i          # pause & resume here
        i += 1

for x in first_n(3):
    print(x)

total = sum(x * x for x in range(1_000_000))  # lazy, low memory
print(total)
Output
0
1
2
(large sum)

Think Beyond the Expected

What If?

Why use a generator instead of returning a full list for a huge dataset?

A list materializes every element in memory at once; a generator yields one at a time, using near-constant memory — essential for large files, database cursors, or infinite streams. The trade-off: a generator is single-pass (consumed once) and has no len() or indexing.

Real World

Streaming lines from a multi-GB file, paginating an API, or building data pipelines all use generators so memory stays flat regardless of data size — a core scalability tool in Python.

Interviewer's Expectation

Keywords they're listening for:

  • yield produces lazily
  • keeps state between calls
  • constant memory
  • single-pass/consumed once
  • generator expression

Common Mistakes

  • Trying to reuse an exhausted generator
  • Calling len() or indexing a generator
  • Building a list when a generator would scale better

Best Practices

  • Use generators for large/streaming data
  • Use generator expressions for one-pass pipelines
  • Remember they're single-use

Follow-up Questions

  1. Generator vs list — memory and reuse trade-offs?
  2. What does `yield from` do?
  3. How are generators related to iterators?

Continue Learning with AI

Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.

Plain-language foundations

I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner.

Topic: Generators (Python)
Interview question: "What is a generator and how does yield work?"

Please:
1. Explain the core idea in simple, plain language, using an everyday analogy.
2. Define any technical terms you use.
3. Walk through one small, concrete example.
4. Finish with a single sentence I can easily remember.

Keep the tone friendly and assume I'm new to this topic.
Open inChatGPTGeminiClaude

Was this answer helpful?

Affiliate links

Equipment for a comfortable, productive setup.

As an Amazon Associate I earn from qualifying purchases.