Control Flow

Generators in Python

Generators are functions used to create an iterable sequence of values.

def generator_name(params):
        yield value #value returned on each loop iteration

#for each through generator
for i in generator_name()
    #execute code for each i

#storing a generator and iterating
generator_variable = generator_name()

#generator expression (similar to list comprehension but returns a generator)
generator = (var_with_operations for var in some_list boolean_expression)


The yield line is used to return the value on each iteration.

def square_numbers():
    i = 1
    while True:
        yield i**2
        i = i + 1

See Also

Generators - Python Wiki

Add to Slack

< With Statement   |   Functions >

© 2019 SyntaxDB. All Rights Reserved.