PYTHON

Implement a Fixed-Size Queue with Python's deque

Learn to create a high-performance fixed-size queue using `collections.deque` in Python, ideal for managing recent items or logs efficiently.

from collections import deque

# Create a fixed-size deque (queue) with a maximum length of 3
recent_activity = deque(maxlen=3)

# Add items to the queue
recent_activity.append("User A logged in")
print(f"Current activity: {list(recent_activity)}")

recent_activity.append("User B viewed profile")
print(f"Current activity: {list(recent_activity)}")

recent_activity.append("User C posted comment")
print(f"Current activity: {list(recent_activity)}")

# Adding a new item automatically removes the oldest one
recent_activity.append("User A updated settings")
print(f"Current activity (oldest item removed): {list(recent_activity)}")

# Deques also support popping from both ends efficiently
oldest_event = recent_activity.popleft()
print(f"Popped oldest event: {oldest_event}")
print(f"Remaining activity: {list(recent_activity)}")
How it works: The `collections.deque` (double-ended queue) is a list-like container offering O(1) time complexity for appending and popping elements from both ends, unlike Python lists which are slow for `pop(0)` and `insert(0)`. When initialized with `maxlen`, it becomes a fixed-size queue. If more items are added than `maxlen`, elements are automatically removed from the opposite end, making it perfect for use cases like storing recent history, logs, or implementing circular buffers.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs