Stack, queue, deque
Python list as a stack, why lists fail as queues, and how collections.deque solves it with O(1) operations on both ends.
Stack
A stack is a Last In First Out (LIFO) structure — the last element you add is the first one you remove. Think of a stack of plates: you always take from the top.
A Python list works perfectly as a stack. Both operations are O(1):
| Operation | List method | Complexity |
|---|---|---|
| Push | append(x) | O(1) |
| Pop | pop() | O(1) |
| Peek | lst[-1] | O(1) |
| Size | len(lst) | O(1) |
| Empty check | len(lst) == 0 | O(1) |
Example: Checking Balanced Brackets
A classic stack application — for every opening bracket push it, for every closing bracket pop and verify it matches:
Example: Reversing a List with a Stack
Queue
A queue is a First In First Out (FIFO) structure — the first element added is the first one removed. Think of a line of people: whoever arrives first gets served first.