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?
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With