Discussion:
deque slicing
Steven Bethard
2004-09-15 06:27:59 UTC
Permalink
Even getitem/setitem were a stretch (they perform best at endpoints) and were
added to make deques substitutable for lists in stack/queue applications
using d[0] and d[-1] to implement peekleft() and peekright() operations.
Ahh, ok, so the functionality I was really looking for is peekleft(n). That
is, a peek function that would return the first n items, starting at the
left. (If you're curious why I wanted this, see the peekable class in
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373.) I assumed
that the best way to get this was slicing, but are there plans for such a
peekleft function?

Steve
Steven Bethard
2004-09-14 18:28:00 UTC
Permalink
Anyone know why deques don't support slicing?
from collections import deque
d = deque(i**2 - i + 1 for i in range(10))
d
deque([1, 1, 3, 7, 13, 21, 31, 43, 57, 73])
d[:5]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: sequence index must be integer
[d[i] for i in range(5)]
[1, 1, 3, 7, 13]

Is there a performance problem with supporting slicing perhaps?

Steve
--
You can wordify anything if you just verb it.
- Bucky Katt, Get Fuzzy
Raymond Hettinger
2004-09-15 05:45:17 UTC
Permalink
Post by Steven Bethard
Anyone know why deques don't support slicing?
In part, it is because of the vague notion that slicing is not what deques are
all about. While it's easy to add a getslice operation, setslice and delslice
require rearranging data outside the slice range. To me, that is a strong
indicator that an application needs a list instead of a deque.

Even getitem/setitem were a stretch (they perform best at endpoints) and were
added to make deques substitutable for lists in stack/queue applications using
d[0] and d[-1] to implement peekleft() and peekright() operations.

Deques emulate some but not all of the list API. The parts that match were done
to make deques easier to learn and to make them more substitutable for lists in
stack/queue apps. The rest of the API was excluded because the list structure
was more appropriate for those operations.


Raymond

Loading...