Stacks & Queues (deque)
Part of the Python Roadmap
In short
Undo buttons, browser back history, matching brackets, print jobs and breadth-first search all come down to two simple structures: a stack (last in, first out) and a queue (first in, first out).
A stack is last-in-first-out and a queue is first-in-first-out. In Python, a list works as a stack with append() and pop(), and collections.deque is the right choice for queues.

Think of it like this
Plates and the ticket queue
At a shaadi buffet, you take the top plate from the stack, the one put down most recently. At the railway ticket counter, the person who came first is served first. Same people, two different rules: that's a stack versus a queue.
Watch it happen
Is "{[()]}" balanced?
Top of the stack is coloured
1/6An opening bracket: push it.
The big ideas
What you need to know
list as a stack
append() pushes and pop() removes from the end. Both are O(1). Check if stack: before popping.
deque as a queue
collections.deque has append() and popleft(), both O(1). Perfect for queues.
Not list.pop(0)
Popping from the front of a list shifts every other item, which is O(n). It quietly slows big queues down.
Spot the pattern
Most recent first (undo, brackets, DFS) means stack. Oldest first (orders, BFS) means queue.
See it in code
Walk through the code
1from collections import deque2 3PAIRS = {")": "(", "]": "[", "}": "{"}4 5 6def is_balanced(text: str) -> bool:7 stack: list[str] = []8 for ch in text:9 if ch in "([{":10 stack.append(ch)11 elif ch in PAIRS:12 if not stack or stack.pop() != PAIRS[ch]:13 return False14 return not stack15 16 17print(is_balanced("{[()]}")) # True18print(is_balanced("([)]")) # False19 20tokens = deque(["A101", "A102"])21tokens.append("A103") # a new customer joins at the back22serving = tokens.popleft() # serve from the front in O(1)23print(serving, list(tokens)) # A101 ['A102', 'A103']1/4Openers go on the stack.
A stack checks brackets; a deque runs a bank token queue.
Save yourself the pain
Common mistakes
Oops
Calling stack.pop() without checking that the stack has items.
Do this instead
Popping an empty list raises IndexError. Check if not stack first, as in is_balanced.
Oops
Using list.pop(0) for a queue of thousands of items.
Do this instead
Use deque.popleft(), which is O(1) instead of O(n).
Oops
Forgetting the final empty check in bracket matching.
Do this instead
"(((" has no mismatches but is still unbalanced. Return not stack at the end.
Your mission
Build a browser history
Quick check
Which structure and method should you use to remove items from the front of a queue efficiently in Python?
Go deeper
- 1Check if brackets in an expression are balanced using a stack.
- 2Simulate a ticket counter queue with deque.
- 3Avoid list.pop(0), which is slow, and use deque.popleft() instead.
More topics at this stop
Stuck on this topic? Ask an Insider
Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.