How would you extract items 3..6 efficiently, elegantly and pythonically from the following deque
without altering it:
from collections import d
I'd add this as a new answer, to provide better formatting.
For simplicity, Shawn's answer is perfect, but if you often need to get a slice from dequeue
, you might prefer to subclass it and add a __getslice__
method.
from collections import deque
from itertools import islice
class deque_slice(deque):
def __new__(cls, *args):
return deque.__new__(cls, *args)
def __getslice__(self, start, end):
return list(islice(self, start, end))
This won't support setting a new slice, but you can implement your own custom __setslice__
method using the same concept.
NOTE: this is valid for Python <=2.* only. It's also worth noticing that, while __getslice__
is deprecated since python 2.0, the documentation still reports this for the latest 2.7 release:
(However, built-in types in CPython currently still implement
__getslice__()
. Therefore, you have to override it in derived classes when implementing slicing.)