Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace values in an array or list continuously

I am very new to coding and I was wondering if it is possible to limit an array in python to 100 items.

If it is possible, can you keep adding to that array and pushing out the old numbers in the array? So the oldest number should be pushed out to make room each time a new number is added.

Thank you very much in advance!

like image 258
Matthew Keron Avatar asked Jan 27 '18 04:01

Matthew Keron


2 Answers

Yes, it's possible via collections.deque:

from collections import deque

lst = deque([], 100)

Like list.append, deque.append works in place:

A = deque(range(10), maxlen=10)

print(A)

deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)

A.append(10)

print(A)

deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], maxlen=10)
like image 127
jpp Avatar answered Oct 16 '22 23:10

jpp


What about creating a simple function to do this:

def add_to_array(lst, item, maxsize):

    if len(lst) >= maxsize:
        lst.pop(0)

    lst.append(item)

Which works like this:

>>> lst = [i for i in range(1, 10)]
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> add_to_array(lst, 10, 10)
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> add_to_array(lst, 11, 10)
>>> lst
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

Note: If your looking for something more efficient, you can use collections.deque, as pointed out in the other answer.

Here is an example of using deque to emulate your desired behaviour:

>>> lst = deque((i for i in range(1, 10)), maxlen=10)
>>> lst
deque([1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=10)
>>> lst.append(10)
>>> lst
deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], maxlen=10)
>>> lst.append(11)
>>> lst
deque([2, 3, 4, 5, 6, 7, 8, 9, 10, 11], maxlen=10)
like image 6
RoadRunner Avatar answered Oct 16 '22 23:10

RoadRunner