Search⌘ K

Nested Comprehensions

Explore nested list comprehensions in Python to create complex lists and 2D lists efficiently. Understand how to nest loops within comprehensions, control elements based on multiple variables, and compare these patterns with equivalent for loops for better code clarity.

We'll cover the following...

You can create nested list comprehensions. In fact, there are a couple of ways to do it.

Creating a 2D list

Possibly the easiest example of a nested list comprehension is to nest one comprehension inside another. For example:

Python 3.8
a = [[x for x in range(3)] for y in range(4)]
print(a)

We know that [x for x in range(3)] gives [0, 1, 2]. So, we are really calculating [[0, 1, 2] for y in range(4)],

which, of course, ...