0

I was trying something out with python where I have a 2d list that I am populating using another list. Everything works out fine, but when I print out the contents of the list I have populated, it only prints out the last row of the list I copied from.

a= [[1, 1], [2,2], [3, 3]]

b= [[0]*len(a[0])]*len(a)

#copying
for i in range(0,len(a)):
  for j in range(0,len(a[0])): 
    b[i][j] = a[i][j]

#printing
for i in range(0,len(b)):
  for j in range(0,len(b[0])):  
    print(b[i][j])

expected output:

1 
1
2 
2
3
3

actual output:

3 
3 
3 
3
3
3

I initially thought it was a scope issue, but in that case shouldn't my output just be 0s? I am not sure how I can resolve this.

  • Hope you are doing list concatenation of elements `b = sum(a, list)` would work i guess – Naga kiran Aug 03 '21 at 15:07
  • For a brief explanation, each of your sublists in `b` are identical. That is they all point to the same object, so if you change something in one it's reflected in the others. – Alex Aug 03 '21 at 15:14

0 Answers0