Suppose we have a deque
with maxlen=3
. If the deque
already have 3 items and when I append
a new item, how can I get the item that's going to be discarded?
The reason is that I want to maintain a window in memory that only contains the last N item, and when the window is full and one item is to be discarded, I need to get that item and do some extra work.
Here's my current solution:
from collection import deque
MAX_LEN=10
q = deque(maxlen=MAX_LEN)
while True:
if len(q) == MAX_LEN:
discarded = q.popleft()
process(discarded)
q.append(some_var)
Is this the best I can get? I've thought of using list
and slice the list to limit size/get discarded item, but the if
is unavoidable. Using deque
at least I can get O(1)
performance in the push
and popleft
operation.
Any ideas?