Manage Both Ends with deque
Core idea
A deque(iterable, maxlen=None) supports efficient insertion and removal at either end. Use append and pop on the right, appendleft and popleft on the left. With a positive maxlen, adding to a full deque at one end discards an item at the opposite end.
from collections import dequequeue = deque(["regular"])queue.appendleft("urgent")queue.append("later")print(queue.popleft())print(list(queue))The urgent request is placed at the front; popleft removes it first.
Keep three recent readings
from collections import dequehistory = deque([18, 19, 20], maxlen=3)history.append(21)print(list(history))The oldest leftmost reading is discarded automatically.
Rotate a queue
from collections import dequeturns = deque(["A", "B", "C"])turns.rotate(-1)print(list(turns))A negative rotation shifts items left; positive rotates right.
Common mistake
Popping an empty deque raises IndexError. Test emptiness when needed. Indexing the middle is not an efficient replacement for list random access.
Practice
Keep only the last three readings of a stream; try an empty stream and one with five readings.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Double-ended queues
Check your understanding of deque.
What is printed?
from collections import dequed = deque([4, 2])d.appendleft(1)d.pop()print(list(d))What is printed?
from collections import dequed = deque([1, 2], maxlen=2)d.appendleft(8)print(list(d))Which exception occurs?
from collections import dequedeque().popleft()When is deque preferable to a list?