Generator Expressions

Learn how to utilize generator expressions

Before going into the details and nuances of generators, let's take a quick look at how generators relate to a concept that we have already seen: comprehensions. A generator in the form of a comprehension is called a generator expression.

How generator expressions work

Generators save a lot of memory, and since they are iterators, they are a convenient alternative to other iterables or containers that require more space in memory such as lists, tuples, or sets.

Much like these data structures, they can also be defined by comprehension, only that they are called a generator expression. (There is an ongoing argument about whether they should be called generator comprehensions. In this course, we will just refer to them by their canonical name, but feel free to use whichever you prefer).

In the same way, we would define a list comprehension. If we replace the square brackets with parentheses, we get a generator that results from the expression. Generator expressions can also be passed directly to functions that work with iterables, such as sum() and max():

Get hands-on with 1200+ tech skills courses.