Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant change the values of a matrix using for loop

Tags:

python

I have a matrix M with float numbers. I want to round said numbers to 3 decimals and update the matrix. However, M doesn't change. Why is M not updating?

M= [[1.0, 0.6666666666666666, 0.0, 0.5098039215686274], [-0.0, -0.0, 1.0, 0.4117647058823529]]
for arr in M:
    for number in arr:
        number = round(number, 3)
print(M) #[[1.0, 0.6666666666666666, 0.0, 0.5098039215686274], [-0.0, -0.0, 1.0, 0.4117647058823529]]
like image 943
Fullaccess Avatar asked Nov 16 '25 04:11

Fullaccess


1 Answers

Don't change an array while iterating over it. Instead, store your changes elsewhere. You can set M = rounded_M at the end if you like.

M = [[1.0, 0.6666666666666666, 0.0, 0.5098039215686274], [-0.0, -0.0, 1.0, 0.4117647058823529]]
rounded_M = []

for arr in M:
    rounded_arr = []
    for number in arr:
        rounded_arr.append(round(number, 3))
    rounded_M.append(rounded_arr)

print(rounded_M)
like image 75
Collin Bell Avatar answered Nov 18 '25 18:11

Collin Bell