How to Use deque in Python: Syntax and Examples
collections.deque in Python to create a double-ended queue that allows fast appends and pops from both ends. Import it with from collections import deque, then create a deque with deque() and use methods like append(), appendleft(), pop(), and popleft().Syntax
The deque is imported from the collections module. You create a deque by calling deque() optionally with an iterable. You can add items to the right with append() or to the left with appendleft(). Remove items from the right with pop() or from the left with popleft().
from collections import deque d = deque([1, 2, 3]) # Create a deque with initial items d.append(4) # Add 4 to the right end d.appendleft(0) # Add 0 to the left end right_item = d.pop() # Remove and return item from right left_item = d.popleft() # Remove and return item from left
Example
This example shows how to create a deque, add items to both ends, and remove items from both ends. It prints the deque after each operation to show the changes.
from collections import deque d = deque([10, 20, 30]) print('Initial deque:', d) d.append(40) print('After append(40):', d) d.appendleft(5) print('After appendleft(5):', d) right = d.pop() print('After pop():', d, '| Popped:', right) left = d.popleft() print('After popleft():', d, '| Popped:', left)
Common Pitfalls
One common mistake is using a list when you need fast appends and pops from both ends; lists are slow for popping from the front. Another is forgetting to import deque from collections. Also, using pop() or popleft() on an empty deque raises an IndexError.
Always check if the deque is not empty before popping or handle the exception.
from collections import deque d = deque() # Wrong: popping from empty deque causes error # d.pop() # IndexError # Right: check before popping if d: d.pop() else: print('Deque is empty, cannot pop')
Quick Reference
| Method | Description |
|---|---|
| deque(iterable) | Create a deque with optional initial items |
| append(x) | Add item x to the right end |
| appendleft(x) | Add item x to the left end |
| pop() | Remove and return item from the right end |
| popleft() | Remove and return item from the left end |
| extend(iterable) | Add multiple items to the right end |
| extendleft(iterable) | Add multiple items to the left end (reversed order) |
| clear() | Remove all items from the deque |
| rotate(n) | Rotate the deque n steps to the right (left if negative) |