Skip to content
Python: Handle a full bounded deque before inserting

Python: Handle a full bounded deque before inserting

November 25, 2026

A bounded deque drops an item from the opposite end when you append beyond its capacity. Inserting into a full deque instead raises IndexError. Choose which behavior your queue is allowed to have.

Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.

Run the example

Save this as bounded_queue_demo.py in an empty working directory:

from collections import deque

recent = deque(["a", "b", "c"], maxlen=3)
recent.append("d")
print("After append:", list(recent))
before = list(recent)
try:
    recent.insert(1, "x")
except IndexError:
    print("Full insert rejected")
print("Unchanged:", list(recent) == before)
recent.popleft()
recent.insert(1, "x")
print("After making room:", list(recent))

Run it without -O so any assertions remain enabled:

python3 bounded_queue_demo.py

Captured output:

After append: ['b', 'c', 'd']
Full insert rejected
Unchanged: True
After making room: ['c', 'x', 'd']

The append discards a, leaving the newest three values. The failed insertion leaves the deque unchanged. Removing one item explicitly creates room for the later insertion, so the discard decision is visible.

Limits and cleanup

A bounded deque suits a recent-history buffer. It does not provide backpressure for work that must never be lost. Use an appropriate queue with explicit full handling for that case. Checking length and then inserting is not an atomic multi-threaded operation.

After testing, remove the example script from its working directory:

rm -- bounded_queue_demo.py

Reference

Python 3.12 documentation

Acknowledgements

This post was created with assistance from AI.

Last updated on