Skip to Content
Expert Python Programming - Third Edition
book

Expert Python Programming - Third Edition

by Michał Jaworski, Tarek Ziadé, Cody Jackson
April 2019
Intermediate to advanced
646 pages
16h 48m
English
Packt Publishing
Content preview from Expert Python Programming - Third Edition

Generators and yield statements

Generators provide an elegant way to write simple and efficient code for functions that return a sequence of elements. Based on the yield statement, they allow you to pause a function and return an intermediate result. The function saves its execution context and can be resumed later, if necessary.

For instance, the function that returns consecutive numbers of the Fibonacci sequence can be written using a generator syntax. The following code is an example that was taken from the PEP 255 (Simple Generators) document:

def fibonacci():    a, b = 0, 1    while True:        yield b        a, b = b, a + b

You can retrieve new values from generators as if they were iterators, so using the next() function or for loops:

>>> fib = fibonacci() ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Expert Python Programming - Fourth Edition

Expert Python Programming - Fourth Edition

Michał Jaworski, Tarek Ziade, Tarek Ziadé

Publisher Resources

ISBN: 9781789808896Other