Back
+15 XP
Concept

`collections.deque`: $O(1)$ Double-Ended Queues

Standard Python lists take $O(n)$ time to `pop(0)` or `insert(0)` because elements shift 🐌. `collections.deque` adds and pops from both ends in blazingly fast $O(1)$ time 🚀.

python
from collections import deque

dq = deque([1, 2, 3], maxlen=3)
dq.appendleft(0)  # Pushes to front at O(1) speed!
dq.append(4)      # Pushes to back, auto-evicting 0! 🏎️
print(list(dq))   # [1, 2, 4]

# 28. `collections.deque`: $O(1)$ Double-Ended Queues Standard Python lists take $O(n)$ time to `pop(0)` or `insert(0)` because elements shift 🐌. `collections.deque` adds and pops from both ends in blazingly fast $O(1)$ time 🚀: ```python from collections import deque dq = deque([1, 2, 3], maxlen=3) dq.appendleft(0) # Pushes to front at O(1) speed! dq.append(4) # Pushes to back, auto-evicting 0! 🏎️ print(list(dq)) # [1, 2, 4] ``` Using a standard Python list as a queue in a high-traffic web server is an instant performance bottleneck. When handling incoming request streams, always reach for `deque`. ⚡ --- ### Question Why is `collections.deque` dramatically faster than a standard list for FIFO queues? 🏎️ - [ ] a. Because pushing or popping from the front takes $O(1)$ time instead of shifting all memory in $O(n)$ time - [ ] b. Because deques run in assembly code directly inside CPU cache - [ ] c. Because lists only work on numbers 🔢 - [ ] d. Because deques disable garbage collection entirely 💀 --- ### Challenge Create a `deque` with items `[10, 20]`. Use `.appendleft(5)` to insert 5 at the front. Convert to `list()` and print it. 🎯 <details> <summary>Solution</summary> ```python from collections import deque dq = deque([10, 20]) dq.appendleft(5) print(list(dq)) ``` </details>

Checkpoint

Why is `collections.deque` dramatically faster than a standard list for FIFO queues? 🏎️

Practice

Create a `deque` with items `[10, 20]`. Use `.appendleft(5)` to insert 5 at the front. Convert to `list()` and print it. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks