How would you extract items 3..6 efficiently, elegantly and pythonically from the following deque
without altering it:
from collections import d
This is an old question, but for any future travelers, the Python docs explicitly recommend using rotate
for this:
The rotate() method provides a way to implement deque slicing and deletion.
https://docs.python.org/2/library/collections.html
An implementation is relatively simple:
def slice_deque(d, start, stop, step):
d.rotate(-start)
slice = list(itertools.islice(d, 0, stop-start, step))
d.rotate(start)
return slice
Effectively the same as using islice
directly, except that rotate
is more efficient for skipping through to the starting point. On the other hand, it also temporarily modifies the deque, which could be a threadsafety concern.