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.