Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating over a deque in two directions efficiently in Python

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)

like image 962
user1999728 Avatar asked Jul 22 '26 00:07

user1999728


1 Answers

From the C source reversed([deque]) returns a reverse iterator, no copies or memory allocation. [deque].reverse() will reverse it in place.

like image 105
csunday95 Avatar answered Jul 23 '26 18:07

csunday95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!