How to get element to be dropped in python deque?

Suppose a dequec maxlen=3. If I dequealready have 3 elements, and when I am appenda new element, how can I get the element to be discarded?

The reason is because I want to save a window in memory that contains only the last element N, and when the window is full and one element needs to be dropped, I need to get this element and do additional work.

Here is 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 thought to use listand slice the list to limit the size / get the discarded item, but ifis inevitable. Using dequeat least I can get performance O(1)in operations pushand popleft.

?

+3
1

- .

def pairwise(iterable, n=2 ):
    from itertools import tee, islice, izip
    return izip(*(islice(it,pos,None) for pos,it in enumerate(tee(iterable, n))))


for values in pairwise(infinite_iterable_generating_your_values, n=3):
    process(values[0])
    if breakconditions:
        break 

:

print [i for i in pairwise(range(10), n=3)]

[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9)]
0

All Articles