Borislav Hadzhiev
Thu Jun 16 2022·1 min read
Photo by Sandra Seitamaa
Use the deque class from the collections
module to create a fixed size queue
in Python, e.g. deq = deque(maxlen=3)
. The class takes a maxlen
argument
that determines the maximum length of the deque.
from collections import deque deq = deque(maxlen=3) deq.extend([1, 2, 3]) print(deq) # 👉️ deque([1, 2, 3], maxlen=3) deq.append(4) print(deq) # 👉️ deque([2, 3, 4], maxlen=3)
We used the
collections.deque
class to initialize a deque
object.
You can also pass an iterable to the class to initialize the deque
object with
items.
from collections import deque # 👇️ initialize deque with items deq = deque([1, 2, 3], maxlen=3) print(deq) # 👉️ deque([1, 2, 3], maxlen=3) deq.append(4) print(deq) # 👉️ deque([2, 3, 4], maxlen=3)
The deque
class takes a maxlen
argument. If the argument is not provided or
is None
, the deque
object can grow to an arbitrary length.
maxlen
argument is provided and the deque
is full, when new items are added, the same number of items are discarded from the opposite end.If we
append
a new item to the deque
, an item from the start of the deque
is discarded.
from collections import deque deq = deque([1, 2, 3], maxlen=3) print(deq) # 👉️ deque([1, 2, 3], maxlen=3) deq.append(4) print(deq) # 👉️ deque([2, 3, 4], maxlen=3)
Conversely, if we use the
appendleft
method to add an item to the left side of the deque
, an item from the end of
the deque
is discarded.
from collections import deque deq = deque([1, 2, 3], maxlen=3) print(deq) # 👉️ deque([1, 2, 3], maxlen=3) deq.appendleft(0) print(deq) # 👉️ deque([0, 1, 2], maxlen=3)