Turning a list comprehension into a generator expression PREMIUM

When can you turn a list comprehension into a generator expression? And more importantly, when can't you? If you're only looping over your list, and only one time, you can use a generator instead.

Trey Hunner Trey Hunner 3 min read 03:13 video Python 3.10—3.15
Watch this as a 03:13 screencast
Same content, narrated.
Watch it

When can you turn a list comprehension into a generator expression?

Passing a comprehension to a function

We're taking a list comprehension that squares a bunch of numbers and passing it into a function that multiplies all those numbers together:

>>> lucas_numbers = [2, 1, 3, 4, 7, 11, 18]
>>> product([n**2 for n in lucas_numbers])
1106493696

Our product function looks like this:

>>> def product(numbers):
...     total = 1
...     for n in numbers:
...         total *= n
...     return total
...

What if we wanted to turn this list comprehension into a generator expression? Would the product function accept a generator object?

>>> product((n**2 for n in numbers))
>>> product((n**2 for n in numbers))
1106493696

When are generator objects acceptable?

List comprehensions build new lists. They do all their work upfront to build that list.

Generator expressions build new generator objects. They delay their work until you loop over them: they do work element-by-element.

There's one thing that you can do with both a list and a generator object, and that is to loop over it... but just one time because generators are lazy single-use iterables.

It turns out our product function only loops over the object that we give to it and it loops only once. It doesn't try to index the object, get its length, slice it, or loop a couple times. It just loops and just one time.

>>> def product(numbers):
...     total = 1
...     for n in numbers:
...         total *= n
...     return total
...

So we can pass a generator object to the product function:

>>> product((n**2 for n in numbers))
1106493696

Generators can be used where "iterables" are expected

We were able to pass a generator expression to our product function, but what about a function that we didn't write?

For example let's say we're passing our list comprehension to the built-in sum function:

>>> sum([n**2 for n in numbers])
524

Could we pass a generator expression to sum instead?

>>> sum((n**2 for n in numbers))
524

We could just try it out and see if it works or we could take a look at the documentation for sum:

>>> help(sum)
Help on built-in function sum in module builtins:

sum(iterable, /, start=0)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers

    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

The sum function claims that it accepts an iterable of numbers.

Generators are iterables; they're lazy iterables and they're single-use iterables, but they are iterables.

So sum should accept a generator because when we see that word iterable used in documentation we can assume that it's the most generic form of the term iterable. The word "iterable" just means something that you're able to iterate over; it doesn't imply that you can iterate more than once.

So sum should accept a generator expression:

>>> sum((n**2 for n in numbers))
524

Removing redundant parentheses

This is such a common use case of generator expressions (passing them directly into another function) that the Python core developers actually made a special syntax just for this use case:

>>> sum((n**2 for n in numbers))
524

If you pass a generator expression in as the sole argument to a function, you can remove the extra parentheses:

>>> sum(n**2 for n in numbers)
524

We're passing a generator expression into the sum function but we don't have two sets of parentheses ((( and ))).

So if you ever see some code that looks like this:

>>> tuple(n**2 for n in numbers)
(4, 1, 9, 16, 49, 121, 324)

This looks kind of like a tuple comprehension, but it's not a tuple comprehension. This is a generator expression passed into the tuple constructor. Tuple comprehensions don't exist, but we can kind of invent our own comprehensions (in a sense) by mashing up generator expressions with other functions and classes.

Summary

So if you have a list comprehension and you're wondering whether you can turn it into a generator expression, you have to ask yourself:

  1. Am I only looping over the list that I'm getting back (no indexing, length checking, etc)?
  2. Am I only looping one time?

If the answer to both of those questions is "yes", then you can turn that list comprehension into a generator expression.

Remember this next month 🧠

Now make sure you remember what you just watched: Daily Recall shows you a few Python questions a day and brings each one back right before you’d forget it.

Next up
Generators are iterators
03:00 watch

Generators aren't data structures. Unlike lists, generators do work as you loop over them, computing their next value only when it's asked for. Generators are iterators (lazy single-use iterables).

Watch
This is a free preview of a premium screencast. You have 2 previews remaining.