Fullaccess
Fullaccess

Reputation: 155

Cant change the values of a matrix using for loop

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]]

Upvotes: 3

Views: 1123

Answers (4)

ask_me
ask_me

Reputation: 473

that is because you are not passing the value back to M. Try this..

M = [[1.0, 0.6666666666666666, 0.0, 0.5098039215686274], [-0.0, -0.0, 1.0, 0.4117647058823529]]
for arr in M:
    new_arr = [round(x, 3) for x in arr]
    arr[:] = new_arr[:]
print(M)  # [[1.0, 0.667, 0.0, 0.51], [-0.0, -0.0, 1.0, 0.412]]

Upvotes: 0

Adib
Adib

Reputation: 9

You're actually not changing the values within the list. To change (mutate) a list item, you must call the item by its index. (There are other ways, but this is the most common.) For example:

my_list = [1,2,3]
my_list[0] = 4 # Changes 0th item to 4

In your code, you were changing the number variable, but this won't affect the list. The best way, in this case, would be (as Collin stated) to create a separate list.

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

A = [] # New list to store the rounded numbers

for sublist in M:
    A.append([round(number, 3) for number in sublist])

The code above uses what are called list comprehensions. Esentially, they're like compact for-loops. This code is saying: return an array of rounded numbers for every number in the sublist of M and add it to the new list A.

Upvotes: 0

scaryhamid
scaryhamid

Reputation: 400

basically you are not assigning anything to "M". you need to store the numbers that you are generating and round function just returns a value that you are assigning it to "number" and not "M".

M= [[1.0, 0.6666666666666666, 0.0, 0.5098039215686274], [-0.0, -0.0, 1.0, 0.4117647058823529]]
temp2=list()
for arr in M:
    temp=list()
    for number in arr:
        number = round(number, 3)
        temp.append(number)
    temp2.append(temp)
print(temp2)

Upvotes: 0

Collin Bell
Collin Bell

Reputation: 384

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)

Upvotes: 2

Related Questions