This question already has an answer here:
I've changed some code that used a list to using a deque. I can no longer slice into it, as I get the error:
TypeError: sequence index must be integer, not 'slice'
Here's a REPL that shows the problem.
>>> import collections
>>> d = collections.deque()
>>> for i in range(3):
... d.append(i)
...
>>> d
deque([0, 1, 2])
>>> d[2:]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence index must be integer, not 'slice'
So, is there a workaround to support slicing into deques in Python?
If performance is a concern, consider a direct access/comprehension method as suggested in this answer. It's much faster than
islice
on large collections:As per @RaymondHettinger comment below, the comprehension method is only better when slices are short. On longer slices,
islice
convincingly wins. For example, here are timings for slicing a 10,000 items deque from the offset 6000:The comprehension does first few slices very fast, but the performance falls down dramatically as the length grows.
islice
is slower on smaller slices, but its average speed is much better.This is how I tested:
Try
itertools.islice()
.Indexing into a
deque
requires following a linked list from the beginning each time, so theislice()
approach, skipping items to get to the start of the slice, will give the best possible performance (better than coding it as an index operation for each element).You could easily write a
deque
subclass that does this automagically for you.Note that you can't use negative indices or step values with
islice
. It's possible to code around this, and might be worthwhile to do so if you take the subclass approach. For negative start or stop you can just add the length of the deque; for negative step, you'll need to throw areversed()
in there somewhere. I'll leave that as an exercise. :-)The performance of retrieving individual items from the
deque
will be slightly reduced by theif
test for the slice. If this is an issue, you can use an EAFP pattern to ameliorate this somewhat -- at the cost of making the slice path slightly less performant due to the need to process the exception:Of course there's an extra function call in there still, compared to a regular
deque
, so if you really care about performance, you really want to add a separateslice()
method or the like.