23

Since a deque is a doubly linked list, I should be able to iterate through it in order without any performance cost compared to a list. However, the following will be much slower than iterating through a list

for i in range(0, len(d)):
    doSomethingWith(d[i])

Since each time it goes to d[i] starting at d[0]. How do I make it iterate properly?

1

2 Answers 2

32

You can directly iterate over the deque.

for i in d:
    doSomethingWith(i)

(see the examples in the documentation: https://docs.python.org/2/library/collections.html#collections.deque)

0
9

I used a while loop for deque iteration, as follows:

from collections import deque

lst = [1,2,4,8]
queue=deque(lst)

print(queue)

while queue:
    print('{}{}'.format("head: ",queue[0]))
    queue.popleft()

output:

deque([1, 2, 4, 8])
head: 1
head: 2
head: 4
head: 8
2
  • 1
    This answer is very useful in case, you want to delete my iterating the queue. Mar 30, 2021 at 5:27
  • 1
    Indeed, this is useful if you want to use the dequeue as an actual FIFO queue until empty
    – Alex
    Oct 20, 2021 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.