Radu
Radu

Reputation: 803

appending numpy arrays to python list overwrites existing elements in list

I am trying to get a python list of numpy arrays, by appending to an initially empty list in a loop. The problem is this: the new array to be added is computed correctly, the list gets expanded by this new element but every element in the list gets overwritten with this new element. Here is the code:

from numpy import *

pos = array([0., 0, 0])
vel = array([1., 0, 0])
t, tf, dt = 0., 1, 0.1
ppos = [pos]
while t < tf:
    pos += vel*dt
    ppos.append(pos) 
    t += dt

Thanks

Upvotes: 1

Views: 2422

Answers (1)

kirelagin
kirelagin

Reputation: 13616

It's not overwritten, you are just always appending the same array. pos += vel*dt adds to pos array in-place, it doesn't create a new one. So you end up with a list consisting of a number of references to this same array.

You'll have to numpy.copy it each time.

Upvotes: 4

Related Questions