Alex Rivera | Logout

How can I pop() lots of elements from a deque?

Asked 2012-02-29T22:26:37.340
31

I have a deque object what holds a large amount of data. I want to extract, say, 4096 elements from the front of the queue (I'm using it as a kind of FIFO). It seems like there should be way of doing this without having to iterate over 4096 pop requests.

Is this correct/efficient/stupid?

A = arange(100000)
B = deque()
C = [] # List will do 
B.extend(A) # Nice large deque

# extract 4096 elements
for i in xrange(4096):
   C.append(A.popleft())
Edit
Report

1 Answer

5

Where you're using a deque the .popleft() method is really the best method of getting elements off the front. You can index into it, but index performance degrades toward the middle of the deque (as opposed to a list that has quick indexed access, but slow pops). You could get away with this though (saves a few lines of code):

A = arange(100000)
B = deque(A)
C = [B.popleft() for _i in xrange(4096)]
answered 2012-02-29T22:43:09.683

Your Answer