Generator examples
Now that you know how generators can be created, let’s look at a few useful generators and examples of how to use them.
Before you start writing a generator for your project, always make sure to look at the Python itertools
module. It features a host of useful generators that cover a vast array of use cases. The following sections show some custom generators and a few of the most useful generators in the standard library.
These generators work on all iterables, not just generators. So, you could also apply them to a list
, tuple
, string
, or other kinds of iterables.
Breaking an iterable up into chunks/groups
When executing large amounts of queries in a database or when running tasks via multiple processes, it is often more efficient to chunk the operations. Having a single huge operation could result in out-of-memory issues; having many tiny operations can be slow due to start-up/teardown sequences.
To make things more efficient...