Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Defining generator functions with the yield statement


A generator function has properties similar to a generator expression. Rather than a single expression, a generator function is a full Python function. It has all of the features of the functions described in Chapter 7, Basic Function Definitions. It has the additional characteristic of being an iterator, capable of generating a sequence of items.

When we use a yield statement, the semantics of the function are changed. Without a yield, a function will return a single value. With a yield statement, a function will behave like an iterator, providing multiple values to a consumer.

Here's an example of a generator function that applies a range of values to a model to compute a domain of results. We'll apply the model to a sequence of input values to compute the results for each input:

def model_iter(until):
    for n in range(0, until):
        yield n*(n+1)//2

This model_iter() function accepts a single argument, until, which is the number...