deque
- Python course
- Intermediate
- Lesson 91/116
- 5 min
Learn double-ended queues with deque.
deque
A deque (double-ended queue) is a data structure that supports fast addition and removal at both ends. It comes from the collections module; unlike a list, operations at the front run in O(1) time.
Example: d = deque([1, 2, 3]). With d.appendleft(0) you add to the front, with d.append(4) to the end. d.popleft() removes from the front, d.pop() from the end. The same operations on a list take O(n); this is why deque is preferred for queue tasks.
Difference from list
On a list, calling insert(0, x) or pop(0) shifts all items; so it runs in O(n) time. A deque uses a doubly-linked structure to do these in O(1).
For queue (FIFO) or stack (LIFO) applications, deque is much more efficient than a list. If you pass a maxlen argument, the deque drops old items automatically once the length is exceeded; this is useful for sliding-window tasks.
Practice Add to the front of deque
Start with from collections import deque. Create a deque with d = deque([1, 2, 3]). Add 0 to the front with d.appendleft(0). Then print the deque as a list with print(list(d)).
Starter code
# Add 0 to the front of dequeSample solution
# Add 0 to the front of deque
from collections import deque
d = deque([1, 2, 3])
d.appendleft(0)
print(list(d))Expected output
[0, 1, 2, 3]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the deque methods
| Term | Meaning |
|---|---|
append |
Add to end |
appendleft |
Add to front |
pop |
Remove from end |
popleft |
Remove from front |
2 When is appendleft preferred on a deque?
- When fast front insertion is needed Correct answer
- Only for end removal
- Only for search operations
- Only for sequential access
Explanation: appendleft adds to the front in O(1); this is hard with a list.
3 appendleft call
from collections import deque
d = deque([1, 2, 3])
d.____(0)
print(list(d))
from collections import deque
d = deque([1, 2, 3])
d.appendleft(0)
print(list(d))
Explanation: appendleft adds 0 to the front.