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?
You can directly iterate over the deque.
The iterator() method of Deque Interface returns an iterator over the elements in this deque in a proper sequence. The elements will be returned in order from first (head) to last (tail). The returned iterator is a “weakly consistent” iterator.
A deque is a double-ended queue in which elements can be both inserted and deleted from either the left or the right end of the queue. An implementation of a deque in Python is available in the collections module.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With