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!
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With