The difference of list derivation between Python 2 and Python 3

tested a list derivation that cannot be run in Python 3. Can Daniel give me an explanation?

-sharp python2  
matrix = [[1,2,3],[4,5,6],[7,8,9]]
[x for row in matrix for x in row]
-sharp  [1, 2, 3, 4, 5, 6, 7, 8, 9]
[x for x in row for row in matrix]
-sharp  [7, 7, 7, 8, 8, 8, 9, 9, 9]
-sharp python3  
matrix = [[1,2,3],[4,5,6],[7,8,9]]
[x for row in matrix for x in row]
-sharp  [1, 2, 3, 4, 5, 6, 7, 8, 9]
[x for x in row for row in matrix]
-sharp Traceback (most recent call last):
-sharp  File "<stdin>", line 1, in <module>
-sharp NameError: name "row" is not defined
Feb.28,2021

this has nothing to do with python. You can run the test because you run [x for row in matrix for x in row] first, and then the row variable exists, so there is no error


.

your second way of writing [x for x in row for row in matrix] is wrong. You first execute [x for row in matrix for x in row] in python2, and then row is declared. Do not believe you print (row) , or you execute

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

[x for row in matrix for x in row]

[x for x in _row for _row in matrix]

see if the last sentence is wrong

Menu