Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D List Comprehension to For loop

Tags:

python

I'm trying to convert the following list comprehension to a normal for loop, mainly because I don't quite understand how it works yet:

board = [ [3 * j + i + 1 for i in range(3)] for j in range(3) ]

Creates a 2D array with values: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

My code:

board = []
for j in range(3):
    for i in range(3):
        board.append(3*j+i+1)

Creates a 1D array with values: [1, 2, 3, 4, 5, 6, 7, 8, 9]

like image 843
henry-js Avatar asked Jan 25 '26 03:01

henry-js


2 Answers

The internal loop saves values ​​in the internal lists. The external loop stores the lists in the external list

board = []
for j in range(3):
    board2=[]
    for i in range(3):
        board2.append(3*j+i+1)
    board.append(board2)
print(board)

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

Explanation

simply in each cycle of the loop an element of the list is created. This is the simplest case:

[j for j in range(3)]
[0, 1, 2]

now in each cycle of the loop simply create a list with the index:

[[j] for j in range(3)]

[[0], [1], [2]]

Now we use the same mechanism to declare the internal list:

[[j for j in range(3)] for j in range(3)]
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

now we make the values ​​of the internal lists depend on the external index:

[ [3 * j  for i in range(3)] for j in range(3) ]
[[0, 0, 0], [3, 3, 3], [6, 6, 6]]

finally we increase depending on the internal index:

[ [3 * j + i + 1 for i in range(3)] for j in range(3) ]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
like image 182
ansev Avatar answered Jan 27 '26 17:01

ansev


You need to use an intermediate list to store the results:

board = []
for j in range(3):
    row = []
    for i in range(3):
        row.append(3*j+i+1)
    board.append(row)

print(board)

Output

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
like image 45
Dani Mesejo Avatar answered Jan 27 '26 16:01

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!