2

I have a very simple question about nested for loops in Python (perhaps applicable to other languages).

Here's a minimal example:

my_array = [[0]*10]*10
k = 0
for i in range(10):
    for j in range(10):
        my_array[i][j] = k
        k += 1 

After executing these lines, I would expect my_array to look like a matrix with the digits 0 through 99 written out left to right top to bottom.

Instead my_array looks like this:

[[90, 91, 92, 93, 94, 95, 96, 97, 98, 99],
 [90, 91, 92, 93, 94, 95, 96, 97, 98, 99],
 [90, 91, 92, 93, 94, 95, 96, 97, 98, 99],
 [90, 91, 92, 93, 94, 95, 96, 97, 98, 99],
 [90, 91, 92, 93, 94, 95, 96, 97, 98, 99],
 [90, 91, 92, 93, 94, 95, 96, 97, 98, 99],
 [90, 91, 92, 93, 94, 95, 96, 97, 98, 99],
 [90, 91, 92, 93, 94, 95, 96, 97, 98, 99],
 [90, 91, 92, 93, 94, 95, 96, 97, 98, 99],
 [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]]

Somehow it seems k is only being evaluated according to its values on the last run of the outermost i loop.

Does anyone understand what Python is doing here? Using the product function from ittertools produces (as the documentation makes clear) the same result. Also, replacing range(10) with either a tuple or a list of the digits 0 through 9 produces the same result.

  • 1
    As well as the existing answers: https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list –  May 18 '20 at 18:20
  • As a simple workaround use `my_array = np.array([[0]*10]*10)`. – Code Pope May 18 '20 at 18:20
  • 1
    You can go read the already-answered question linked from the close request, but the problem has nothing to do with the logic or nested for loops. It's all down to that original assignment: `[[0]*10]*10` doesn't create 10 unique arrays, but 10 references to the same single array representing a row. And the only reason that one row doesn't consist of 10 pointers to the same numeric value (which would make your whole array contain nothing but `99`'s) is that integers are value types rather than reference types in Python. – Mark Reed May 18 '20 at 18:21
  • 1
    The problem isn't with the loops, but with how you construct `my_array` – hpaulj May 18 '20 at 18:21

0 Answers0