Truncate the list to the maximum number of items

I would like to remove the old elements (like the first ones) of the list so that the list does not exceed 100 elements.

I thought about:

L = [327983, 232382, 1, 2, 3, 4, 5, 6, 23]

if len(L) > 100:
    for i in range(len(L)-100):
        del L[0]

print L    # [4, 5, 6, 23]

      

Is there a no-iteration solution (or, more generally, a nicer solution) for trimming the beginning of the list so that it has <= 100 elements?


Sidenote: Isn't there something other than lists for this? that is, the data structure that has the maximum size, and if more data arrives, the oldest are deleted! (This makes me think of FIFO? Stack? Pipe?)

+3


source to share


2 answers


You can just assign the fragment back to the list



L = L[-100:]

      

+3


source


How about using it collection.deque

? If you specify maxlen

, it will not save any more items maxlen

.



>>> from collections import deque
>>> q = deque([1, 2, 3], maxlen=3)
>>> q
deque([1, 2, 3], maxlen=3)
>>> q.append(4)
>>> q
deque([2, 3, 4], maxlen=3)

      

+5


source







All Articles