3

I would like to remove the oldest-added (i.e. the first) elements of a list, such that this list never exceeds 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 solution without iteration (or more generally: a nicer solution) for trimming the beginning of the list, so that it has <= 100 elements?


Sidenote: Isn't there something else than lists, for this purpose? i.e. a data structure that has a maximum size, and such that if more data comes, the oldest are deleted! (It makes me think about FIFO? Stack? Pipe?)

Basj
  • 41,386
  • 99
  • 383
  • 673

2 Answers2

8

How about using collection.deque? If you specify maxlen, it will not store more than maxlen elements.

>>> 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)
falsetru
  • 357,413
  • 63
  • 732
  • 636
4

You can just assign a slice back to your list

L = L[-100:]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218