May 2017
Intermediate to advanced
310 pages
8h 5m
English
We can create functions that do not just return one result, but rather an entire sequence of results, by using the yield statement. These functions are called generators. Python contains generator functions, which are an easy way to create iterators and they are especially useful as a replacement for unworkably long lists. A generator yields items rather than build lists. For example, the following code shows why we might choose to use a generator as opposed to creating a list:
# compares the running time of a list compared to a generator import time #generator function creates an iterator of odd numbers between n and m def oddGen(n, m): while n < m: yield n n += 2 #builds a list of odd numbers between n ...