19.3: Generator expressions

Think Python 2ed. · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    19.3: Generator expressions

    Generator expressions are similar to list comprehensions, but with parentheses instead of square brackets:

    >>> g = (x**2 for x in range(5))
    >>> g
    <generator object <genexpr> at 0x7f4c45a786c0>
    

    The result is a generator object that knows how to iterate through a sequence of values. But unlike a list comprehension, it does not compute the values all at once; it waits to be asked. The built-in function next gets the next value from the generator:

    >>> next(g)
    0
    >>> next(g)
    1
    

    When you get to the end of the sequence, next raises a StopIteration exception. You can also use a for loop to iterate through the values:

    >>> for val in g:
    ...     print(val)
    4
    9
    16
    

    The generator object keeps track of where it is in the sequence, so the for loop picks up where next left off. Once the generator is exhausted, it continues to raise StopIteration:

    >>> next(g)
    StopIteration
    

    Generator expressions are often used with functions like sum, max, and min:

    >>> sum(x**2 for x in range(5))
    30

    This page titled 19.3: Generator expressions was last modified on Tue, 01 Dec 2020 03:30:48 GMT and is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.