Control Flow

Generators in Python

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


Syntax
def generator_name(params):
    some_type_of_loop
        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_variable.next()

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

Notes

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


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

See Also
Documentation

Generators - Python Wiki

Add to Slack

< With Statement   |   Functions >

© 2018 SyntaxDB. All Rights Reserved.