1

I want to create an array or list which only contains 3 entries at any given time. The function should loop and with each loop 1 entry will be added to the list pushing the oldest value out and then a value will be calculated based on the 3 values in the list.

I have tried:

import numpy as np

z = np.ndarray((3,),float)

np.append(z, [12, 14.56, 12.46, 1.56])

which creates a numpy array with only 3 values (afaik) however the array is populated with strange values:

z= ([  1.56889217e-163,   1.01899555e-297,   1.03395110e-297])

anyone know why/what I'm doing wrong or have a better solution for what I want to do?

2 Answers 2

5

Use a deque:

from collections import deque
z = deque(maxlen=3)
z.extend([1, 2, 3, 4])
print z
# deque([2, 3, 4], maxlen=3)
z.append(5)
# deque([3, 4, 5], maxlen=3)
print z

You can also appendleft and extendleft on a deque if you need to.

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

Comments

2

z is being initialized as an empty array. Those strange values are just random numbers that were in the empty memory slots before z was created. You need to have an initial value.

Start with:

z = np.array([14.56, 12.46, 1.56])

And then modify its values, but don't append (that changes the size of the array).

Then here's an example of a function that will 'roll' the elements of your array back by one (or any number) and then replace the first value with a new value.

def push(a, n):
     a = np.roll(a, 1)
     a[0] = n
     return a

Of course, instead of n, you want to use your function of a. For example, if you want to append the sum of the original array to the beginning:

def push_sum(a):
     a = np.roll(a, 1)
     a[0] = a.sum()
     return a

Then:

In [19]: z = np.array([14.56, 12.46, 1.56])

In [20]: push(z, 14)
Out[20]: array([ 14.  ,  14.56,  12.46])

In [29]: push_sum(z)
Out[29]: array([ 28.58,  14.56,  12.46])

3 Comments

way does the output have more than 3 items?
It does indeed, that was mainly because I was trying to find out which value it would drop in that case, but this answers my question anyway
@mark Trying to assign N values to an array of length ≠ N will just give you a ValueError

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.