Stacks and Queues β LIFO vs FIFO
After completing this topic
You will be able to explain the principles of stacks and queues, and understand where each is used.
Stack β Stacking Dishes
A stack is a data structure where you add and remove elements only from the top.
βββββββ
push β β 30 β β pop (remove the most recently added element first)
βββββββ€
β 20 β
βββββββ€
β 10 β
βββββββIt's like stacking dishes in a restaurant. You take the dish that was placed on top last. This is called LIFO (Last In, First Out).
stack = []
# push β add to the topstack.append(10)stack.append(20)stack.append(30)print(stack) # [10, 20, 30]
# pop β remove from the toptop = stack.pop()print(top) # 30 (the last element added)print(stack) # [10, 20]
# peek β check the top element without removing itprint(stack[-1]) # 20Where Stacks Are Used
| Use Case | Description |
|---|---|
| Undo (Ctrl+Z) | Undo the last action first |
| Browser Back | Go back to the last visited page |
| Function Call Stack | Return from the most recently called function first |
| Bracket Validation | Check if parentheses ({[]}) are matched correctly |
Queue β Standing in Line
A queue is a data structure where you add elements to the back and remove them from the front.
enqueue β ββββββ¬βββββ¬βββββ β dequeue
β 10 β 20 β 30 β
ββββββ΄βββββ΄βββββ
front rearIt's like a checkout line at a convenience store. The person who came first gets served first. This is called FIFO (First In, First Out).
from collections import deque
queue = deque()
# enqueue β add to the backqueue.append(10)queue.append(20)queue.append(30)print(queue) # deque([10, 20, 30])
# dequeue β remove from the frontfront = queue.popleft()print(front) # 10 (the first element added)print(queue) # deque([20, 30])You can also implement a queue using Python's list, but list.pop(0) is slow because it has to shift all elements forward. deque provides O(1) performance for both end operations.
Where Queues Are Used
| Use Case | Description |
|---|---|
| Printer Queue | Print documents in the order they were sent |
| Task Scheduling | Process tasks in the order they were requested |
| BFS (Breadth-First Search) | Visit nodes starting from the nearest one |
| Message Queue | Ensure the order of messages between servers |
Stack vs Queue Comparison
| Feature | Stack | Queue |
|---|---|---|
| Principle | LIFO (Last In, First Out) | FIFO (First In, First Out) |
| Analogy | Stacking dishes | Standing in line |
| Add | push (to the top) | enqueue (to the back) |
| Remove | pop (from the top) | dequeue (from the front) |
| Python | list.append() + list.pop() | deque.append() + deque.popleft() |
Practical Example: Bracket Validation (Using a Stack)
def is_valid_brackets(s): stack = [] pairs = {')': '(', ']': '[', '}': '{'}
for char in s: if char in '([{': stack.append(char) elif char in ')]}': if not stack or stack[-1] != pairs[char]: return False stack.pop()
return len(stack) == 0
print(is_valid_brackets("({[]})")) # Trueprint(is_valid_brackets("([)]")) # Falseprint(is_valid_brackets("((")) # FalseWhen you encounter an opening bracket, push it onto the stack. When you encounter a closing bracket, pop from the stack and check if it matches the closing bracket. The LIFO property of the stack perfectly matches the rule that "the most recently opened bracket must be closed first."