How to create a list so that when I append a variable the first element gets removed from list after a certain threshold

Question:

Let’s say I want to create a list. The list need to have a MAX length of 5. The list would operate as such:

list = []
list.append(1)
list = [1]
list.append(2)
list = [1,2]
..
list.append(5)
list = [1,2,3,4,5]

But, when I append another number the first element is removed:

list.append(6)
list = [2,3,4,5,6]

This is super basic and I can’t figure this one out.

I don’t want to use classes – can this be done with basic functions such as slices?

Asked By: Ariel Tarayants

||

Answers:

You could use a collections.deque for this:

>>> import collections
>>> data = collections.deque(maxlen=5)
>>> data.append(1)
>>> data.append(2)
>>> data.append(3)
>>> data.append(4)
>>> data.append(5)
>>> data
deque([1, 2, 3, 4, 5], maxlen=5)
>>> data.append(6)
>>> data
deque([2, 3, 4, 5, 6], maxlen=5)
>>>

Note, this can pretty much work like a list object, however, it does have different performance characteristics, perhaps most importantly, no random access (basically, a linked list of arrays, but it won’t have constant-time access like an array-list, which is what a list object is).

However, it is particularly meant for these types of operations, a "double-ended queue", it allows for efficient removal and addition at both ends. A list can only efficiently append and pop, but adding / removing from the beginning will be inefficient.

Answered By: juanpa.arrivillaga

Use deque() from collections. It will hold certain amount of variables, after that it will delete the first item while appending.

If you don’t want to use libraries or classes, you can simply create a list with N none values inside it, then loop inside the list to replace the values inside it.

Answered By: Olca Orakcı

If you need it to be a list, you can use a slightly different approach to add the items (in-place):

L = []
L[:] = L[-4:] + [1] # [1]
L[:] = L[-4:] + [2] # [1, 2]
L[:] = L[-4:] + [3] # [1, 2, 3]
L[:] = L[-4:] + [4] # [1, 2, 3, 4]
L[:] = L[-4:] + [5] # [1, 2, 3, 4, 5]
L[:] = L[-4:] + [6] # [2, 3, 4, 5, 6]

Which you could place in a function to make it easier to use:

def appendMax(L,maxLen,value):            # maxLen > 1
    L[:] = L[1-maxLen:] + [value]

L = []
appendMax(L,5,1) # [1]
appendMax(L,5,2) # [1, 2]
appendMax(L,5,3) # [1, 2, 3]
appendMax(L,5,4) # [1, 2, 3, 4]
appendMax(L,5,5) # [1, 2, 3, 4, 5]
appendMax(L,5,6) # [2, 3, 4, 5, 6]
Answered By: Alain T.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.