generator expressions python code example

Example 1: generator expressions python

>>> even_squares = (x * x for x in range(10)
                    if x % 2 == 0)

Example 2: generator expressions python

>>> for x in even_squares:
...     print(x)
0
4
16
36
64

Example 3: generator expressions python

def generator():
    for item in collection:
        yield expression

Example 4: generator expressions python

>>> genexpr = ('Hello' for i in range(3))
>>> list(genexpr)
['Hello', 'Hello', 'Hello']

Example 5: generator expressions python

>>> listcomp = ['Hello' for i in range(3)]
>>> genexpr = ('Hello' for i in range(3))

Example 6: generator expressions python

>>> iterator = ('Hello' for i in range(3))
>>> for x in iterator:
...     print(x)
'Hello'
'Hello'
'Hello'