Home > Back-end >  Nested loop won't update
Nested loop won't update

Time:06-02

i'm trying to multiply all items in a list by -1, but the list won't update.

the original list goes like:

[[[[-0.04344771 -0.07890235 -0.08350667 ... -0.05058916 -0.02590174
     0.01833121]
   [-0.03187432 -0.06377442 -0.07528157 ... -0.0153968   0.00928687
     0.05289121]
   [-0.0030058  -0.02783908 -0.04554714 ...  0.01647086  0.02895362
     0.05640405]
   ...
   [ 0.00193604  0.03679746  0.06137059 ...  0.04944649  0.06763638
     0.08346977]
   [ 0.01469174  0.04900428  0.0724168  ...  0.09451687  0.08840736
     0.0754609 ]
   [ 0.0307981   0.05116013  0.06343959 ...  0.08668113  0.05572119
     0.01737073]]]]

i try to update it with:

for value in data:
   for a in value:
       for b in a:
           for item in b:
               item = item * -1

but when i try to print the list again, nothing has changed.

When i try to print it however, with:

for value in data:
    for a in value:
        for b in a:
            print(b * -1)

it does print the list correctly:

[-0.0307981  -0.05116013 -0.06343959 ... -0.08668113 -0.05572119
 -0.01737073]

how do i fix this?

CodePudding user response:

You assign to variable, not to list content. You can assign to i-th element of list instead:

for value in data:
   for a in value:
       for b in a:
           for i, item in enumerate(b):
               b[i] = -item

Or use augmented assignment to list item:

for value in data:
   for a in value:
       for b in a:
           for i in range(len(b)):
               b[i] *= -1

CodePudding user response:

This happens because the line

for item in b

copies the value of the item in the innermost array, rather than directly referencing it. For an array that is nested specifically three deep, you'd need to do something like this:

for i in range(len(x)):
    for j in range(len(x[i])):
        for k in range(len(x[i][j])):
            for l in range(len(x[i][j][k])):
                x[i][j][k][l] *= -1

This changes the actual values rather than creating a copy, since the line x[i][j][k][l] *= -1 changes the value stored in the array as opposed to a copy

  • Related