How to Implement Deque in Python: Syntax and Examples
In Python, you can implement a
deque (double-ended queue) using the collections.deque class, which allows fast appends and pops from both ends. Import it with from collections import deque, then create a deque object and use methods like append(), appendleft(), pop(), and popleft().Syntax
The deque class is imported from the collections module. You create a deque by calling deque() optionally with an iterable. Key methods include:
append(item): Add item to the right end.appendleft(item): Add item to the left end.pop(): Remove and return item from the right end.popleft(): Remove and return item from the left end.
python
from collections import deque # Create an empty deque d = deque() # Create a deque with initial items d2 = deque([1, 2, 3]) # Add to right end d.append(4) # Add to left end d.appendleft(0) # Remove from right end item_right = d.pop() # Remove from left end item_left = d.popleft()
Example
This example shows how to create a deque, add items to both ends, and remove items from both ends.
python
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)
Output
Initial deque: deque([10, 20, 30])
After append(40): deque([10, 20, 30, 40])
After appendleft(5): deque([5, 10, 20, 30, 40])
After pop(): deque([5, 10, 20, 30]) | Popped: 40
After popleft(): deque([10, 20, 30]) | Popped: 5
Common Pitfalls
Common mistakes include:
- Using a list instead of deque for frequent pops/appends on both ends, which is slower.
- Forgetting to import
dequefromcollections. - Using
pop(0)on a list to remove from the front, which is inefficient compared topopleft()on deque.
python
from collections import deque # Wrong: Using list for queue operations queue = [1, 2, 3] queue.pop(0) # Slow for large lists # Right: Using deque for efficient pops from left queue = deque([1, 2, 3]) queue.popleft() # Fast operation
Quick Reference
| Method | Description |
|---|---|
| append(item) | Add item to the right end |
| appendleft(item) | Add item 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 |
| rotate(n) | Rotate deque n steps to the right (left if negative) |
Key Takeaways
Use collections.deque for fast appends and pops from both ends.
Import deque with 'from collections import deque' before using it.
Avoid using list pop(0) for queue operations; use deque.popleft() instead.
Deque supports adding/removing items from both ends efficiently.
Use deque methods like append, appendleft, pop, and popleft for common operations.