How to create a Fixed size Queue in Python

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

Create a Fixed size Queue in Python #

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.

main.py
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.

main.py
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.

If the 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.

main.py
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.

main.py
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)
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.