0

I'm getting trouble setting values inside of a List of lists. I want to change the values through nested for loops one value at a time.

q = 3*[ 3*[10.] ]

for i in range(q):
    for j in range(q[0]):
        q[i][j] = 0
        print(i,j,q)

But the for loops change three values at a time. By running the code above, Python 3.7.10 gives

0 0 [[0, 10, 10], [0, 10, 10], [0, 10, 10]]
0 1 [[0, 0, 10], [0, 0, 10], [0, 0, 10]]
0 2 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
1 0 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
1 1 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
1 2 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
2 0 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
2 1 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
2 2 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

How can I change one value at a time?. This belongs to a change in the Python version?

  • when you create `q = 3*[ 3*[10.] ]` the id of the 3 sub arrays is the same (so actually you have only one array [10,10,10] 3 times in q. try creating q as [[10,10,10],[10,10,10],[10,10,10]] that should solve the problem – Ulises Bussi Oct 26 '21 at 15:53

0 Answers0