1

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.