Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use slice notation with collections.deque

How would you extract items 3..6 efficiently, elegantly and pythonically from the following deque without altering it:

from collections import deque q = deque('',maxlen=10) for i in range(10,20):     q.append(i) 

the slice notation doesn't seem to work with deque...

like image 542
Jonathan Livni Avatar asked Aug 15 '11 11:08

Jonathan Livni


People also ask

Can you slice a deque in Python?

makes sense to implement slicing in the deque class. The deque iterator has the same internal access to the linked list. You can do it just as efficiently by rotating the deque (unless you need to use the deque concurrently).

How do you use slice notation in Python?

Basic Usage of Slices The full slice syntax is: start:stop:step. start refers to the index of the element which is used as a start of our slice. stop refers to the index of the element we should stop just before to finish our slice. step allows you to take each nth-element within a start:stop range.

Why would you use a deque from the collections module instead of a normal list?

Deque is preferred over a list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity.

What is deque from collections?

Advertisements. A double-ended queue, or deque, has the feature of adding and removing elements from either end. The Deque module is a part of collections library. It has the methods for adding and removing elements which can be invoked directly with arguments.


2 Answers

import itertools output = list(itertools.islice(q, 3, 7)) 

For example:

>>> import collections, itertools >>> q = collections.deque(xrange(10, 20)) >>> q deque([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) >>> list(itertools.islice(q, 3, 7)) [13, 14, 15, 16] 

This should be more efficient the the other solutions posted so far. Proof?

[me@home]$ SETUP="import itertools,collections; q=collections.deque(xrange(1000000))"  [me@home]$ python -m timeit  "$SETUP" "list(itertools.islice(q, 10000, 20000))" 10 loops, best of 3: 68 msec per loop  [me@home]$ python -m timeit "$SETUP" "[q[i] for i in  xrange(10000, 20000)]" 10 loops, best of 3: 98.4 msec per loop  [me@home]$ python -m timeit "$SETUP" "list(q)[10000:20000]" 10 loops, best of 3: 107 msec per loop 
like image 150
Shawn Chin Avatar answered Sep 22 '22 21:09

Shawn Chin


I would prefer this, it's shorter so easier to read:

output = list(q)[3:6+1] 
like image 36
Roshan Mathews Avatar answered Sep 19 '22 21:09

Roshan Mathews