0

I'm new to Python and the following toy problem baffles me:

import numpy as np
V = np.ones([3,3])
Vini = V
Niter = 10
Vlist = list() # collect all iterations
Vlist.append(V)

for it in range(1, Niter-1):
    for ix in range(0,3):
        for iy in range(0,3):
            V[iy,ix] = Vlist[it-1][iy,ix] + 1
    Vlist.append(V) # save current iteration

(note that I am not after efficiency improvements – this is purely for didactic purposes)

My issue is that all elements of Vlist are identical, where I expected them to differ (by 1) at each iteration. Even Vini has changed its value! Is this a shallow/deep copy kind of thing, or something else? How do I fix this, and how do I reason about this kind of thing? (coming from other languages where a=b means deep copy).

  • You keep appending a reference to the same list: `V` – Mark Jul 30 '20 at 06:26
  • "My issue is that all elements of Vlist are identical" *because you keep appending the same `numpy.ndarray` object on each iteration*: `Vlist.append(V)` so of course, `Vlist` simply contains the same object over and over. This has nothing to do with shallow vs deep copy, this has to do *with copying versus not copying*. To get different objects, use `Vlist.append(V.copy())` – juanpa.arrivillaga Jul 30 '20 at 06:28

1 Answers1

1

Note that a variable holding an object in Python is something like a "pointer" to the actual object (in other languages).

Your intention is to save in Vlist the curent content of V, so each time you append something to Vlist, you should append a copy of the object in question.

So change your code to:

Vlist.append(V.copy())
for it in range(1, Niter-1):
    for ix in range(0,3):
        for iy in range(0,3):
            V[iy,ix] = Vlist[it-1][iy,ix] + 1
    Vlist.append(V.copy())

By the way: You can generate just the same result running:

Vlist.append(V.copy())
for it in range(1, Niter-1):
    V += 1
    Vlist.append(V.copy())
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41