iterating over a deque in two directions efficiently in Python
Question:
I have a deque, let’s call it deq
. I need to iterate over it from both ends, and I will not be modifying it at all during these iterations.
Naturally, I don’t want to create another deque.
I’ve considered reversed
, but I don’t know if it actually creates any copies. If, for example, I were write:
reversed_deq = reversed(deq)
will it reference the exact same memory locations, but simply iterate over it in reverse, without using any more memory/time?
That seems like the logical way to go for a double-ended queue, but I want to make sure I’m not missing anything.
I can’t find the code for deque (usually they have a “python equivalent” of these things, but I couldn’t find it), and for some reason – no matter what I run – timeit
always gives me something between 15 and 16 ns (for everything I try to time, not just this)
Answers:
From the C source reversed([deque])
returns a reverse iterator, no copies or memory allocation. [deque].reverse()
will reverse it in place.
Python 2 and 3 documentation states that the reversed()
built-in function “returns a reverse iterator”. Strictly speaking, this does not prevent an implementation of collections.deque.__reversed__()
to make copies. In practice, there is no reason why it would make copies, since a deque is naturally iterable in both directions.
I have a deque, let’s call it deq
. I need to iterate over it from both ends, and I will not be modifying it at all during these iterations.
Naturally, I don’t want to create another deque.
I’ve considered reversed
, but I don’t know if it actually creates any copies. If, for example, I were write:
reversed_deq = reversed(deq)
will it reference the exact same memory locations, but simply iterate over it in reverse, without using any more memory/time?
That seems like the logical way to go for a double-ended queue, but I want to make sure I’m not missing anything.
I can’t find the code for deque (usually they have a “python equivalent” of these things, but I couldn’t find it), and for some reason – no matter what I run – timeit
always gives me something between 15 and 16 ns (for everything I try to time, not just this)
From the C source reversed([deque])
returns a reverse iterator, no copies or memory allocation. [deque].reverse()
will reverse it in place.
Python 2 and 3 documentation states that the reversed()
built-in function “returns a reverse iterator”. Strictly speaking, this does not prevent an implementation of collections.deque.__reversed__()
to make copies. In practice, there is no reason why it would make copies, since a deque is naturally iterable in both directions.