1

I'm writing something where I am popping and appending often and thought it would be appropriate to use deque. However, somewhere in my code I need to divide the deque in two.

Consider the deque d

from collections import deque

d = deque(range(4))

I'd like to split the deque in this way

d[:2]

But I get an error

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-29-cb523bbbf363> in <module>()
      3 d = deque(range(4))
      4 
----> 5 d[:2]

TypeError: sequence index must be integer, not 'slice'

I could do

list(d)[:2]

[0, 1]

But that seems absurd to turn it back into a list just to slice it. Am I wrong? Or is there another way?

piRSquared
  • 285,575
  • 57
  • 475
  • 624

1 Answers1

2

With itertools.islice, you can do

deque(islice(d, 2))
user2357112
  • 260,549
  • 28
  • 431
  • 505