LANGUAGE REFERENCE · /python/deque/
deque in Python
Use a deque when you append or pop at both ends. A Python list is O(n) on the left, because removing the first item shifts every remaining element down one place.
You can couple or uncouple a carriage at either end of a train in one move, and a deque works the same way. A list is more like a numbered row of chairs: take the front one away and everybody has to shuffle up a seat.
Try all four ends
A deque is the same container whether it acts like a stack or a queue. Add and remove items at either end, then set maxlen=3 to see which item silently falls off.
The deque is empty. Add an item at either end.
The Python-specific detail
Because those blocks are linked rather than contiguous, indexing into the middle is O(n) while both ends are O(1). That is the reason q[len(q)//2] inside a loop is the classic way to make a deque slower than the list it replaced — the mirror image of the cost a level-order tree walk pays when it takes from the front of a plain list instead.
The second surprise is maxlen : it discards silently from the opposite end. Perfect for a rolling window, quietly destructive if you expected an exception — the same kind of silent wrong outcome as an API that replays a stored response and sends the confirmation email a second time, because the email was never part of the record.