Python 3D Academyবাংলা

Comprehensions inside comprehensions

🌍 In real life. To read every seat number in a cinema, you go row by row, and along each row seat by seat: two loops, one inside the other. And to set up a new hall, you build each row of empty seats, then the rows together.

Comprehensions can do both jobs, using two for parts or one comprehension inside another.

The idea in one sentence: two for parts in one comprehension run like nested loops, the first one outside, and a comprehension inside another builds a list of lists.

Its words:

  • flatten: turn a grid into one plain list: [x for row in grid for x in row]
  • nested comprehension: [[0] * 3 for _ in range(2)] makes a new row on each lap
  • _: the usual name for a loop variable you don't use

Step by step, for [x for row in grid for x in row] with grid [[1, 2], [3, 4]]:

  1. The first for takes row [1, 2]; the second takes 1, then 2.
  2. The first for takes row [3, 4]; the second takes 3, then 4.
  3. The result is [1, 2, 3, 4].
grid = [[1, 2], [3, 4]]
flat = [x for row in grid for x in row]
print(flat)

A comprehension can also make a list of lists. When you don't need the loop variable, it's usual to call it _:

board = [[0] * 3 for _ in range(2)]
print(board)
table = [[r * c for c in range(1, 4)] for r in range(1, 4)]
print(table)

The expression can even hold another comprehension. Here, for each number, we count how many numbers in the list are smaller:

nums = [8, 1, 2, 2, 3]
print([len([m for m in nums if m < n]) for n in nums])
Short is not always clear! If a comprehension gets hard to read, a normal for loop is a fine choice.

What it costs. Two for parts do outer × inner laps, just like nested loops. The last example is costlier than it looks: for each of the n numbers, the inner comprehension walks all n numbers again, so it does n × n steps. Fine for 5 numbers; for 10,000 it's 100 million.

Mistakes and edge cases.

  • The for parts in the wrong order. [x for x in row for row in grid] uses row before it exists: NameError: name 'row' is not defined. Write them in the same order as nested loops.
  • [[0] * 3] * 2 again. That shares one row; the comprehension [[0] * 3 for _ in range(2)] makes a new row each lap.
  • Too clever to read. If you can't read a comprehension aloud in one breath, write the loops out.

Quiz

  1. What does this print?

    print([x for row in [[1], [2, 3]] for x in row])
  2. What does this print?

    print([[0] * 2 for _ in range(2)])
  3. What does this print?

    print([[r * c for c in range(2)] for r in range(1, 3)])
  4. In [x for row in grid for x in row], which loop is the outer one?

    • for row in grid
    • for x in row
    • They run side by side
  5. What does this print?

    print(len([1 for a in range(3) for b in range(2)]))
  6. Which line stops this program with an error?

    grid = [[1, 2], [3, 4]]
    flat = [x for x in row for row in grid]
    print(flat)

Coding tasks

  1. Here is a grid: grid = [[1, 2, 3], [4, 5, 6]]. Print it flattened into one list.

  2. Ask for a whole number n. Print the n by n multiplication table as a list of lists. For n = 2: [[1, 2], [2, 4]].

  3. Ask for whole numbers on one line. For each number, count how many numbers in the list are smaller than it. Print the list of counts.