🐍 Python Beginner

What are Python generators?

Why Interviewers Ask This

This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex Python topics. It also reveals how well you can explain technical ideas to non-experts.

Answer

A generator is a function that uses yield to produce a series of values lazily — one at a time — instead of returning all values at once. When called, it returns a generator iterator. Each next() call on the iterator runs until the next yield, pausing execution there. Example: def fibonacci(): a, b = 0, 1; while True: yield a; a, b = b, a+b. Iterate: for n in fibonacci(): if n > 100: break; print(n). Generators use almost no memory for large sequences — they compute each value on demand. yield from iterable delegates to a sub-iterator. Generator expressions: (x**2 for x in range(10)). Use generators for large data streams (reading large files line-by-line), infinite sequences, and data pipelines where you do not need all data at once.

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Python answers easy to follow.