PYTHON

Manage Efficient Queues and Recent Item Lists with Python `collections.deque`

Employ Python's `collections.deque` (double-ended queue) for fast appends and pops from both ends of a collection, perfect for implementing history logs, task queues, or limited-size caches in web applications.

from collections import deque

# Create a deque
history = deque()

# Add items to the right (end)
history.append("page_view_1")
history.append("page_view_2")
history.append("page_view_3")
# deque(['page_view_1', 'page_view_2', 'page_view_3'])

# Add items to the left (beginning)
history.appendleft("initial_load")
# deque(['initial_load', 'page_view_1', 'page_view_2', 'page_view_3'])

# Remove items from the right (end)
last_view = history.pop() # 'page_view_3'
# deque(['initial_load', 'page_view_1', 'page_view_2'])

# Remove items from the left (beginning)
first_item = history.popleft() # 'initial_load'
# deque(['page_view_1', 'page_view_2'])

# Create a fixed-size deque (e.g., for last 3 items)
recent_logs = deque(maxlen=3)
recent_logs.append("log_entry_1")
recent_logs.append("log_entry_2")
recent_logs.append("log_entry_3")
recent_logs.append("log_entry_4") # 'log_entry_1' is automatically removed
# deque(['log_entry_2', 'log_entry_3', 'log_entry_4'])
How it works: A `collections.deque` (double-ended queue) is a list-like container that supports fast appends and pops from both its ends. Unlike standard Python lists, which are inefficient for operations at the beginning, `deque` offers O(1) performance for `appendleft()` and `popleft()`. This makes it ideal for implementing queues, managing recent activity feeds, or creating fixed-size buffers that automatically discard older items when new ones are added.

Need help integrating this into your project?

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

Hire DigitalCodeLabs