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 elements.

If possible, can you continue to add to this array and pop the old numbers in the array? Therefore, the oldest number must be pushed out to free up space each time a new number is added.

Thank you in advance!

+5
source share
2 answers

How about creating a simple function for this:

def add_to_array(lst, item, maxsize): if len(lst) >= maxsize: lst.pop(0) lst.append(item) 

Which works as follows:

 >>> 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 you are looking for something more efficient, you can use collections.deque as mentioned in another answer.

Here is an example of using deque to emulate the desired behavior:

 >>> 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) 
+6
source

Yes, this is possible through collections.deque :

 from collections import deque lst = deque([], 100) 
+12
source

Source: https://habr.com/ru/post/1274979/


All Articles