# How to efficiently calculate velocity from position data stored in list within in a list

Hi,
I am new to python and would like to know how I can efficiently calculate the velocity from a list within a list.
I have a variable x_pos that contains the positions of 6 different people sampled at 10000 points in time. The timestep between all samples is constant = 0.1s. Running the following code thus returns the answer 6:

``````print(len(x_pos))
``````

However if I take the positions of only the first person and check the length of that list:

``````x_pos1 = x_pos
print(len(x_pos1))
``````

The answer is 10000. This thus returns the length of the list within my original list.
I would like to know how I can calculate the instantaneous velocity of all persons efficiently, where the result is again a list within a list. As a final result I would thus like to have a main list of length 6, where each of the 6 lists inside the main list are of length 9999.

Thanks for your help!

It may help if we could see the data structure; your data stored in a `list[]` within a `list[]`.

Also, is that ‘baked in’, or are you open to having an alternative data structure?

Is the positional data 1-dimensional? If so, you can do:

``````dt = 0.1
velocity = []
for person in x_pos:
velocity.append([(x2 - x1) / dt for x1, x2 in zip(person, person[1:])]
``````

Or, a faster implementation using numpy (speed difference won’t be large for just 60000 data points, though):

``````import numpy as np

dt = 0.1
velocity = []
for person in x_pos:
velocity.append(np.diff(person) / dt)
``````

If the positional data is in some other format you will have to specify what it is.

1 Like

I indeed have 1D data and your solution works perfectly. Thank you!

1 Like