🎁 New User? Get 20% off your first purchase with code NEWUSER20 Register Now →
Menu

Categories

Python Intermediate

What is Generator?

A function that yields values one at a time using the yield keyword, enabling memory-efficient iteration over large datasets.

Generators produce values lazily — they compute the next value only when requested. This makes them ideal for processing large files, infinite sequences, or data streams without loading everything into memory.

A generator function uses yield instead of return. Generator expressions use parentheses: (x**2 for x in range(1000000)) creates a generator without allocating memory for all values.