1

how do I get first n element of dequeue, and then n+1 to 2n element of dequeue and so on.

I know how to do it on list, but using the same method, I get:

from collections import deque
d = deque('ghi')
print d[:2]

I got the following:

$python main.py
deque(['g', 'h', 'i'])
3
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    a = d[:2]
TypeError: sequence index must be integer, not 'slice'
user3222184
  • 1,071
  • 2
  • 11
  • 28
  • Deques don't support slicing. I think that's because it wouldn't work as well as you'd expect, based on how they're stored, but I'm not sure. – Daniel H Nov 01 '18 at 01:57

2 Answers2

2

You can use itertools,

from collections import deque
import itertools

d = deque('ghi')
print (list(itertools.islice(d, 1, 3)))

# output,
['h', 'i']

Or if you want to print as a string,

print (''.join(itertools.islice(d, 1, 3)))

#output,
hi
Sufiyan Ghori
  • 18,164
  • 14
  • 82
  • 110
0

Try itertools.islice()

 deque_slice = collections.deque(itertools.islice(d, 0, 2))

Note that you can't use negative indices or step values with islice.

More details here