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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.