Reputation: 965
I have a list of varying length that I want to continuously up date with some new data. So basically I want to add a new data point and remove any data out of a set range. I have been playing around with this for a little bit now and haven't gotten anywhere that I can tell. I was trying to use this post as a reference, but apparently I don't under stand what is going on. Below is a code snippet that is an example of what I have tried.
for i in range(0,100):
n.append(i)
n = [x for x in n if not (x-n[-1]>10)]
print len(n)
Ideally n would only have the last 10 data points contained in it at any given time during the for loop. I am sure that this is something basic that I am just not understanding, if you all could help me out I would really appreciate it. Thanks.
Edit: Example of the list n
[0]
[0, 1]
...
[89, 90, 91, 92, 93, 94, 95, 96, 97, 99]
Upvotes: 0
Views: 243
Reputation: 80406
use deque with fast appends and pops: and from python 2.7 up you can set maxlen.
from collections import deque
>>> d=deque([])
>>> for i in range(10):
... d.append(i)
... if len(d) > 3: d.popleft()
...
0
1
2
3
4
5
6
>>> d
deque([7, 8, 9])
Using maxlen:
>>> d = deque(range(5), maxlen=3)
>>> print d
deque([2, 3, 4], maxlen=3)
>>> print d.maxlen
3
Upvotes: 0
Reputation: 3108
If I properly understand, you want to keep some variable number of elements in the list "n". Let's call that variable "m", so
for i in range(0,100):
n.append(i)
m = random.randint(1, 10)
if len(n)>m:
n = n[-m:] # [-m:] defines the last m elements of n
print len(n)
This should always print m in the end
Upvotes: 1
Reputation: 1101
Assuming you mean that n should contain only the latest 10 data points inserted, you want:
for i in range(0,100):
n.append(i)
if len(n)>10: n[:] = n[1:]
print len(n) # will never go above 10
Upvotes: 4
Reputation: 25499
Why not just pop()
the list every time you append something, if len>10
? If I'm understanding the question right.
for i in range(0,100):
n.append(i)
if len(n)>10:
n.pop(0)
Upvotes: 4