PYTHON

Implement Fixed-Size Caches and Queues with `collections.deque`

Discover how Python's collections.deque (double-ended queue) efficiently manages fixed-size lists, ideal for maintaining recent item history, activity logs, or limited caches in web applications.

from collections import deque

# Example: Fixed-size history of recent items (e.g., last 5 visited pages)
# maxlen argument ensures the deque never grows beyond that size,
# automatically dropping oldest elements when new ones are added.
recent_items = deque(maxlen=5)

print("Adding items to history:")
recent_items.append("page_A")
recent_items.append("page_B")
recent_items.append("page_C")
print(f"Current history: {list(recent_items)}")

recent_items.append("page_D")
recent_items.append("page_E")
print(f"Current history: {list(recent_items)}")

# When a new item is added, the oldest one (page_A) is automatically removed
recent_items.append("page_F")
print(f"History after adding 'page_F': {list(recent_items)}")

# deque also supports efficient appends/pops from both ends
# Adding to the left (front)
recent_items.appendleft("page_G")
print(f"History after appendleft('page_G'): {list(recent_items)}")

# Removing from the right (end)
popped_right = recent_items.pop()
print(f"Popped from right: {popped_right}, Remaining history: {list(recent_items)}")

# Removing from the left (front)
popped_left = recent_items.popleft()
print(f"Popped from left: {popped_left}, Remaining history: {list(recent_items)}")

# Example for a simple queue (FIFO)
task_queue = deque()
task_queue.append("task1")
task_queue.append("task2")
print(f"Task queue: {list(task_queue)}")
next_task = task_queue.popleft()
print(f"Processed task: {next_task}, Remaining queue: {list(task_queue)}")
How it works: A `collections.deque` (double-ended queue) is a list-like container optimized for fast appends and pops from both ends. Unlike standard Python lists, which are inefficient for operations at the beginning, `deque` offers O(1) performance for `append()`, `appendleft()`, `pop()`, and `popleft()`. Its `maxlen` argument makes it perfect for implementing fixed-size caches, managing recent activity logs, or maintaining a limited history, automatically discarding older elements when the maximum size is reached, a common requirement in many 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