Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

deque

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?

like image 323
Haiyang Avatar asked Nov 01 '13 08:11

Haiyang


People also ask

What is deque Maxlen in Python?

deque ([iterable[, maxlen]]) Returns a new deque object initialized left-to-right (using append() ) with data from iterable. If iterable is not specified, the new deque is empty.

How does Python deque work?

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.

Is deque faster than list Python?

A list is one of the main workhorses in almost every Python script, yet, in some cases, opting for deques can lead to much faster performance. A deque is short for a double-ended queue, which is why it's called so. Double-ended means that it supports adding and removing elements from both ends.


1 Answers

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)
like image 186
Ashwini Chaudhary Avatar answered Sep 21 '22 01:09

Ashwini Chaudhary