Colon Operator with Deques (in Python)

Question:

I was hoping to use the colon operator with my deque but it didn’t seem to work the same as a list.

I was trying something like:

myDeque = deque([0,1,2,3,4,5])
myDequeFunction(myDeque[3:])

This is the error I recieved:
“TypeError: sequence index must be integer, not ‘slice'”

What is the best way to do array slicing with deques?

Asked By: user1357607

||

Answers:

deque objects don’t support slicing themselves, but you can make a new deque:

sliced_deque = deque(list(old_deque)[3:])
Answered By: Amber

collections.deque objects don’t support slicing. It’d be more straightforward to make a new one.

n_deque = deque(list(d)[3:])
Answered By: Makoto

Iterating is probably faster than brute-force methods (note: unproven) due to the nature of a deque.

>>> myDeque = collections.deque([0,1,2,3,4,5])
>>> list(itertools.islice(myDeque, 3, sys.maxint))
[3, 4, 5]
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.