Nested Comprehensions

Let’s discuss how to create nested list comprehensions with the help of the examples provided in the lesson.

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:

Press + to interact
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] ...

Get hands-on with 1400+ tech skills courses.