Write Nested Loop as List Comprehension

Here's how to write the nested loop as a list comprehension.

Why

A list comprehension is nice because it's a single expression that returns a value. This better-supports immutable data structures. If one was to use for loops, multiple nested statements would be required and the modification of an external variable in order to return it.

Python idiomatic style (fwiw) prefers list comprehensions only when a value is returned, such as in a map or reduce situation.

Nested Loop

Let's say that we have a nested loop, where all books of all authors are saved to a database. This list of saved books is returned. You might write it as:

saved: list[Book] = []
for author in authors:
    for book in author.books:
        saved += [update_or_create_book(author, book)]
return saved

There are two for statements and a saved list that is appended to and then returned.

Nested List Comprehension

To write the same loop as a list comprehension, return the innermost expression (here, that's the update_or_create_book call). Then start on the outside loop and write the inside loop last.

return [update_or_create_book(author, book) for author in authors for book in author.books]