Skip to content

    Generators & Iterators

    Python · Intermediate

    Definition

    A generator is a function using yield that produces values lazily, one at a time.

    Saves memory on large or infinite data streams.

    Diagram

    yield 1yield 2yield 3done

    Flowchart

    Define function with yieldCall returns generatornext() runs to next yieldStopIteration ends it

    Example: Squares generator

    def squares(n):
        for i in range(n):
            yield i * i
    print(list(squares(4)))

    Output: [0, 1, 4, 9]

    Complexity

    O(1) memory per item

    Key points

    • Generator expressions use ( )
    • Can only be iterated once

    Interview questions

    return vs yield?

    return ends the function; yield pauses it and resumes on next().

    More Python topics