1

Given the following expressions:

matrix = [[1,2,3],[4,5,6],[7,8,9]]

A matrix is created, then a list comprehension is executed to create a flat list. The comprehension runs from left to right.

flat = [x for row in matrix for x in row]

Subsequently for each row in the matrix its values are squared. How is this comprehension evaluated?

squared = [[x**2 for x in row] for row in matrix]
timgeb
  • 76,762
  • 20
  • 123
  • 145
dcrearer
  • 1,972
  • 4
  • 24
  • 48

1 Answers1

0

The first comprehension is equivalent to:

flat = []
for row in matrix:
    for x in row:
        flat.append(x)

The second comprehension is equivalent to:

squared = []
for row in matrix:
    tmp = []
    for x in row:
        tmp.append(x**2)
    squared.append(tmp)

(Except for creating additional variables in the enclosing scope like x, row, tmp.)

timgeb
  • 76,762
  • 20
  • 123
  • 145