collections.deque (appendleft/popleft)
Efficient queue operations at both ends (O(1) append/pop).
from collections import deque
q = deque(iterable)
q.appendleft(x)
x = q.popleft()This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Efficient queue operations at both ends (O(1) append/pop).
The collections.deque class provides a double-ended queue implementation that is optimized for O(1) performance during appends and pops from both the left and right sides. In contrast, Python's built-in list requires O(n) time for insert(0, x) or pop(0) because it must shift all subsequent elements in memory. Deques are implemented using a doubly-linked list of fixed-size blocks, ensuring memory efficiency and predictable performance for queue-based workflows like Breadth-First Search (BFS) and task scheduling. Key features include the maxlen parameter for creating bounded buffers (circular buffers) and thread-safe, atomic append and pop operations. However, accessing elements by index in the middle of a deque is O(n), so it should not be used as a replacement for lists when frequent random access or slicing is required.
Quick reference
Syntax
from collections import deque
q = deque(iterable)
q.appendleft(x)
x = q.popleft()
See it in practice
Examples
Basic FIFO Queue Operations
from collections import deque
queue = deque(['task1', 'task2'])
queue.append('task3')
queue.appendleft('priority_task')
print(list(queue))
first_out = queue.popleft()
print(f'Processed: {first_out}')
print(f'Remaining: {list(queue)}')['priority_task', 'task1', 'task2', 'task3'] Processed: priority_task Remaining: ['task1', 'task2', 'task3']
Demonstrates the efficiency of appendleft and popleft for managing a prioritized First-In-First-Out workflow.
Implementing a Bounded Circular Buffer
from collections import deque
# Keep only the last 3 log entries
recent_logs = deque(maxlen=3)
for i in range(1, 6):
recent_logs.append(f'Event {i}')
print(f'Current buffer: {list(recent_logs)}')Current buffer: ['Event 1'] Current buffer: ['Event 1', 'Event 2'] Current buffer: ['Event 1', 'Event 2', 'Event 3'] Current buffer: ['Event 2', 'Event 3', 'Event 4'] Current buffer: ['Event 3', 'Event 4', 'Event 5']
Using maxlen allows the deque to automatically discard the oldest items (from the left) when new items are appended (on the right).
Using extendleft for Batch Insertions
from collections import deque
d = deque([10, 20])
# extendleft adds items one by one from the head
d.extendleft([5, 4, 3])
print(list(d))[3, 4, 5, 10, 20]
Shows how extendleft behaves by prepending each element of an iterable individually, which results in the input being reversed relative to the original deque.
Debug faster
Common Errors
LogicError
Cause: Assuming extendleft(iterable) maintains the order of the iterable.
Fix: Reverse the iterable before calling extendleft, or recognize that it performs a series of appendleft calls.
d = deque([10]); d.extendleft([1, 2, 3]) # Result: [3, 2, 1, 10]IndexError
Cause: Attempting to popleft() from an empty deque.
Fix: Check if the deque has elements using 'if my_deque:' before popping, or wrap the call in a try/except block.
d = deque([]); item = d.popleft() # Raises IndexErrorRuntime support
Compatibility
collections.deque available in standard library
Source: MDN Web Docs
Common questions
Frequently Asked Questions
Efficient queue operations at both ends (O(1) append/pop).
LogicError: Reverse the iterable before calling extendleft, or recognize that it performs a series of appendleft calls. IndexError: Check if the deque has elements using 'if eque:' before popping, or wrap the call in a try/except block.