Generators

Let's talk about generators and how they can be useful.

A normal Python function will always return one value, whether it be a list, an integer or some other object. But what if we call a function and it yields a series of values? That is where generators come in. A generator works by “saving” where it last left off (or yielding) and giving the calling function a value. So instead of returning the execution to the caller, it just gives temporary control back. To do this magic, a generator function requires Python’s yield statement.

Side-note: In other languages, a generator might be called a coroutine.

Getting started with generators

Let’s take a moment and create a simple generator!

Get hands-on with 1400+ tech skills courses.