0

I was working on Colab and I had to make csv to 2d array.

But I had never used python before (I was C user) so I'm not skilled at python list.

real = [1, 2]
copy = [[0] * 2] * 4

print(copy)

for j in range(1):
    for i in range(2):
        copy[i][j] = real[i]
        print(copy)

I expected

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

but it works like this

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

Please help me...

sungho
  • 89
  • 5

1 Answers1

0

This is a common error caused by something called shallow lists in python.This can be eliminated by declaring the 2D array in this method

real = [1, 2]
rows, cols = (4, 2)
copy = [[0 for i in range(cols)] for j in range(rows)]
print(copy)
for j in range(1):
   for i in range(2):
      copy[i][j] = real[i]
      print(copy)
Sreeram M
  • 140
  • 10