PYTHON

Implementing a Fixed-Size Queue with collections.deque

Use Python's `deque` (double-ended queue) to efficiently manage a fixed-size collection, perfect for maintaining recent item history or a limited cache in web applications.

from collections import deque

# Create a deque with a maximum size of 5
history = deque(maxlen=5)

# Add elements to the right (most common use case for history)
history.append('page1')
history.append('page2')
history.append('page3')
history.append('page4')
history.append('page5')

print(f"Current history: {list(history)}") # Output: ['page1', 'page2', 'page3', 'page4', 'page5']

# Adding a new element automatically discards the oldest (leftmost)
history.append('page6')
print(f"History after adding 'page6': {list(history)}") # Output: ['page2', 'page3', 'page4', 'page5', 'page6']

# Pop elements from either end
print(f"Popped oldest item: {history.popleft()}") # Output: page2
print(f"History after popleft: {list(history)}") # Output: ['page3', 'page4', 'page5', 'page6']

history.appendleft('page0') # Add to the front
print(f"History after appendleft: {list(history)}") # Output: ['page0', 'page3', 'page4', 'page5', 'page6']
How it works: `collections.deque` (double-ended queue) is a list-like container offering efficient appends and pops from either side. When initialized with the `maxlen` parameter, it automatically discards elements from the opposite end to maintain a fixed size. This makes it ideal for managing recent activity logs, bounded caches, or any scenario requiring a sliding window of data in web applications, offering O(1) performance for adding and removing elements from its ends.

Need help integrating this into your project?

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

Hire DigitalCodeLabs