Skip to Main Content
Python Workout
book

Python Workout

by Reuven M. Lerner
July 2020
Beginner to intermediate content levelBeginner to intermediate
248 pages
6h 58m
English
Manning Publications
Content preview from Python Workout

10 Iterators and generators

Have you ever noticed that many Python objects know how to behave inside of a for loop? That’s not an accident. Iteration is so useful, and so common, that Python makes it easy for an object to be iterable. All it has to do is implement a handful of behaviors, known collectively as the iterator protocol.

In this chapter, we’ll explore that protocol and how we can use it to create iterable objects. We’ll do this in three ways:

We’ll create our own iterators via Python classes, directly implementing the protocol ourselves.

We’ll create generators, objects that implement the protocol, based on something that looks very similar to a function. Not surprisingly, these are known as generator functions.

We’ll also create ...

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

Python for Data Science

Python for Data Science

Yuli Vasiliev
Robust Python

Robust Python

Patrick Viafore

Publisher Resources

ISBN: 9781617295508Supplemental ContentPublisher SupportOtherPublisher WebsiteSupplemental ContentErrata PagePurchase Link