Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First n element of deque

Tags:

python

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'
like image 703
user3222184 Avatar asked Dec 06 '25 22:12

user3222184


1 Answers

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
like image 71
Sufiyan Ghori Avatar answered Dec 08 '25 12:12

Sufiyan Ghori