🐍 Python
Beginner
What are Python generators?
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.