Search code examples
pythonarraysnumpyreferencemutability

Iterating and modifying a list of numpy arrays leave arrays unchanged


Consider the two following codes:

import numpy as np

mainlist = [np.array([0,0,0, 1]), np.array([0,0,0,1])]

for i in range(len(mainlist)):
    mainlist[i] = mainlist[i][0:2]

print(mainlist) # [array([0, 0]), array([0, 0])] => OK!

and:

import numpy as np

mainlist = [np.array([0,0,0, 1]), np.array([0,0,0,1])]

for element in mainlist:
    element = element[0:2]

print(mainlist) # [array([0, 0, 0, 1]), array([0, 0, 0, 1])] => WTF?

I was wondering why, in the second case, the arrays remain unchanged. It does not even throw an error about mutability problems. Could you explain exactly what is going on regarding the behavior of the second code? What would be the right way of doing it instead?


Solution

  • Variable name a --->(point to) np.array([0,0,0, 1])

    Variable name b --->(point to) np.array([0,0,0, 1])

    Variable name mainlist --->(point to) [a, b]

    When you use for element in mainlist:,

    Variable name element --->(point to) np.array([0,0,0, 1])


    When you assign another value to element by element = np.array([]),

    element --->(point to) np.array([])

    But the mainlist is still pointing to [a, b].


    When you use mainlist[0] = np.array([]), you really put np.array([]) on the first place of mainlist, but the a is still pointing to np.array([0,0,0, 1]).