Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read Python comprehension with two expressions?

Tags:

python

I do not quite understand how to read the following comprehension, even though I know what it does:

>>> matrix=[[1,2,3],[4,5,6],[7,8,9]]
>>> [x for row in matrix for x in row]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

So, how does this comprehension translate into natural language? I'm not sure because if I try to divide this expression into two parts x for row in matrix and for x in row they all become nonesense in the context of the task.

like image 230
Jacobian Avatar asked Sep 14 '26 03:09

Jacobian


1 Answers

Just add a new line between fors, and make them regular for loops:

for row in matrix:
    for x in row:
        print x

The order is like the order of such regular loops, as the nested loops should be write outer.

[x for row in matrix for x in row for t in x]
   (level 1) --->  (level 2) ---> (level 3)
           ---> nested loops 
like image 112
Mazdak Avatar answered Sep 15 '26 15:09

Mazdak