14

I was learning how to use deque. Here's what I did:

>>> d = deque([1,2,3,4,5,6], maxlen=3)

I expected that d would contain [1,2,3]. But instead I got:

>>> d
deque([4, 5, 6], maxlen=3)

Isn't this counterintuitive?

Haiyang
  • 1,489
  • 4
  • 15
  • 19
  • If what you want is the first up-to-three values in a list, use `mylist[0:3]`. If you want the same for any iterable object, `itertools.islice(iterable, 3)`. – Steve Jessop Nov 01 '13 at 09:04

4 Answers4

31

From docs:

Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end. Bounded length deques provide functionality similar to the tail filter in Unix. They are also useful for tracking transactions and other pools of data where only the most recent activity is of interest.

So, your code is equivalent to:

>>> from collections import deque
>>> d = deque(maxlen=3)
>>> for i in range(1, 7):
...     d.append(i)
...     print d
...     
deque([1], maxlen=3)
deque([1, 2], maxlen=3)
deque([1, 2, 3], maxlen=3)
deque([2, 3, 4], maxlen=3)
deque([3, 4, 5], maxlen=3)
deque([4, 5, 6], maxlen=3)
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
3

The official doc mentioned this clearly:

Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end.

Leonardo.Z
  • 9,425
  • 3
  • 35
  • 38
1

Not at all, from the docs:

"Returns a new deque object initialized left-to-right (using append()) with data from iterable"

I have mainly used deque objects as buffers for the most recent items. So all the users last 100 actions for example.

aychedee
  • 24,871
  • 8
  • 79
  • 83
  • Although I was interested enough to check it and the implementation of `deque` that I'm using (Python 2.7.5) actually doesn't use `append()`. If I subclass and override `append` it doesn't change the behaviour of initialization. This is a subtle point of Python documentation -- "using `append()`" is shorthand for "with the same effect as the defined behaviour of `append()` for this class", it doesn't imply that there's a point of customization there :-) – Steve Jessop Nov 01 '13 at 09:01
1

It is a design decision. It is more practical to keep more recent elements in the queue. The older are just being poped out from the other end.

Alexander Zhukov
  • 4,357
  • 1
  • 20
  • 31