3

I try creating a matrix using list of list with fixed number of elements. I initialized the matrix with 0 for each cell, then iterate over all the elements and in each cell, I multiply each row and column number like this.

test = [[0] * (10)] * 10
for i in range(10):
    for j in range(10):
        test[i][j] = i * j

When I print test, the result is

[[0, 9, 18, 27, 36, 45, 54, 63, 72, 81], [0, 9, 18, 27, 36, 45, 54, 63, 72, 81], [0, 9, 18, 27, 36, 45,54, 63, 72, 81], [0, 9, 18, 27, 36, 45, 54, 63, 72, 81], [0, 9, 18, 27, 36, 45, 54, 63, 72, 81], [0, 9,18, 27, 36, 45, 54, 63, 72, 81], [0, 9, 18, 27, 36, 45, 54, 63, 72, 81], [0, 9, 18, 27, 36, 45, 54, 63,72, 81], [0, 9, 18, 27, 36, 45, 54, 63, 72, 81], [0, 9, 18, 27, 36, 45, 54, 63, 72, 81]]

It looks like only the last i with i=9 is calculated. What I expect is the result of row and column multiplication. How to do this in python?

calmira
  • 39
  • 7
  • 4
    Possible duplicate of [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Yevhen Kuzmovych Apr 29 '19 at 10:19

2 Answers2

0

I wouldn't instantiate an empty list first, just use a list comprehension.

test = [[i * j for i in range(10)] for j in range(10)]

With Numpy:

size = np.arange(10)

test = size * size[:, None]
QuantumChris
  • 963
  • 10
  • 21
0

In your program list has been cloned to 10 times hence it is producing the last modification to the matrix.

Karthik Vg
  • 108
  • 13