0

I am trying to fill a matrix in python in a straightforward (probably not efficient) way:

coord = [0]*3
coords = [[0]*3]*4

for i in range(4):
    for j in range(3):
        coord[j]= i
    coords[i] = coord
    

I would expect the output for "coords" to be [[0,0,0],[1,1,1],[2,2,2],[3,3,3]]

but instead I am getting [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]]

is my matrix algebra bad, or is there something I don't understand about python?

Ivan Viti
  • 271
  • 2
  • 11
  • Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Luke Woodward Mar 15 '21 at 18:53

1 Answers1

2

The reason for such result is that for each i coords[i] will store the reference to the same object. Modifying coord hence results in modification of every item in coords.

Generaly in Python you do not want to declare list size in advance. You should just declare an empty list and then append new item to it.

Refactoring your code like this will give you desired output

coords = []
for i in range(4):
    coords.append([i]*3)
print(coords)
ktv6
  • 685
  • 1
  • 6
  • 14