Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over deque in python

Tags:

python

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?

like image 954
Elliot Gorokhovsky Avatar asked Jun 27 '15 21:06

Elliot Gorokhovsky


People also ask

Can you iterate over a deque in python?

You can directly iterate over the deque.

Does deque have iterator?

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.

What is deque () in python?

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.


1 Answers

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)

like image 122
NightShadeQueen Avatar answered Nov 15 '22 13:11

NightShadeQueen