← Back to all snippets
PYTHON

Implementing a Double-Ended Queue (Deque) with collections.deque

Learn to use Python's collections.deque for efficient appends and pops from both ends of a sequence, ideal for queues, stacks, and managing recent items.

from collections import deque

# Create a new deque
dq = deque(['a', 'b', 'c'])
print(f"Initial deque: {dq}")

# Add elements to the right (end)
dq.append('d')
print(f"After append('d'): {dq}")

# Add elements to the left (beginning)
dq.appendleft('z')
print(f"After appendleft('z'): {dq}")

# Remove elements from the right (end)
popped_right = dq.pop()
print(f"Popped from right: {popped_right}, Deque now: {dq}")

# Remove elements from the left (beginning)
popped_left = dq.popleft()
print(f"Popped from left: {popped_left}, Deque now: {dq}")

# Limit deque size (fixed-size buffer)
history = deque(maxlen=3)
history.append(1)
history.append(2)
history.append(3)
history.append(4) # 1 will be automatically removed
print(f"Fixed-size history: {history}")
How it works: collections.deque (double-ended queue) is a list-like container offering O(1) time complexity for appending and popping elements from both ends. This makes it a highly efficient choice for implementing queues (FIFO), stacks (LIFO), or managing recent item history, unlike standard Python lists where operations on the beginning of the list can be O(n).

Need help integrating this into your project?

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

Hire DigitalCodeLabs