Generators in Python — Python Technical Interview Questions & Answers

Generators in Python

Generators in Python

  • A generator produces values one at a time with yield. def gen(): yield 1; yield 2. for x in gen(): prints 1 then 2. It does not build a full list in memory. Generator expression: (x * x for x in range(10)) — parentheses, not brackets. yield pauses. return ends.
  • Contrast with list comprehension: [...] builds everything now. Generator is lazy. That memory sentence is why interviews ask. next(g) also pulls one value.
  • Generators in Python — output: [1, 2, 3]. yield pauses and continues — not all at once like return.

Technical Interview Tip: yield vs return in one contrast.

Code Examples for Generators in Python

Example

# Generator
def count():
    yield 1
    yield 2
    yield 3

print(list(count()))

Generators in Python — output: [1, 2, 3]. yield pauses and continues — not all at once like return.

How to Explain Generators in Python to an Interviewer

Explain Generators as if you are teaching a junior — definition, then one tiny script.

yield values, lazy. for consumes the generator.

What does the example print, and why?

Generators in Python — output: [1, 2, 3]

What mistake do freshers make with Generators?

≠ list comprehension.