Stack, queue, deque
Understanding of special sequenced data structures: stack, queue, deque
Sequences: Stack, Queue, and Deque
We already know Python lists well. In this lesson we look at how lists can be used as stacks and queues, why that sometimes causes performance problems, and how collections.deque solves them.
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: