← Back to all snippets
PYTHON

Implementing Queues and Fixed-Size History with Python's deque

Learn to use Python's `collections.deque` for efficient appends and pops from both ends, ideal for managing queues, logs, or fixed-size history buffers in web applications.

from collections import deque

# Basic deque operations (acting as a queue)
queue = deque()
queue.append('Task 1') # Add to the right
queue.append('Task 2')
print(f"Queue after appends: {queue}")

task = queue.popleft() # Remove from the left
print(f"Processed task: {task}")
print(f"Queue after popleft: {queue}")

# Adding to the left and removing from the right (acting as a stack)
stack = deque()
stack.appendleft('Item A')
stack.appendleft('Item B')
print(f"Stack after appendlefts: {stack}")
item = stack.pop() # Remove from the right
print(f"Popped item from stack: {item}")
print(f"Stack after pop: {stack}")


# Fixed-size history/cache using maxlen
history = deque(maxlen=3) # Max 3 items
history.append('Visit Page A')
history.append('Visit Page B')
history.append('Visit Page C')
print(f"History (3 items): {history}")

history.append('Visit Page D') # 'Visit Page A' is automatically removed
print(f"History after new append: {history}")

history.appendleft('Visit Page E') # 'Visit Page B' is automatically removed
print(f"History after appendleft: {history}")

# Extending a deque
logs = deque(['Error 1', 'Warning 2'], maxlen=5)
new_logs = ['Info 3', 'Debug 4', 'Critical 5', 'Alert 6']
logs.extend(new_logs) # Extends to the right, pushing out old items if maxlen is reached
print(f"Logs after extend: {logs}")

logs.extendleft(['Notice 7', 'Debug 8']) # Extends to the left
print(f"Logs after extendleft: {logs}")
How it works: This snippet introduces `collections.deque` (double-ended queue), a list-like container that allows for efficient appends and pops from both ends with `O(1)` time complexity, unlike Python's standard lists which are `O(N)` for operations at the beginning. It demonstrates `deque`'s use as a traditional queue (`append()` and `popleft()`) and a stack (`appendleft()` and `pop()`). A key feature is the `maxlen` parameter, which automatically discards elements from the opposite end when new items are added, making `deque` perfect for implementing fixed-size caches, recent history lists, or bounded log buffers in web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs