Why is python deque initialized using the last maxlen items in an iterable?

Haiyang picture Haiyang · Nov 1, 2013 · Viewed 15.9k times · Source

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?

Answer

Ashwini Chaudhary picture Ashwini Chaudhary · Nov 1, 2013

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)