Back to List

Stack and Queue β€” LIFO vs FIFO

Understand what stacks and queues are with real-world analogies and code examples.

Beginner
|
6min
|
Verified (2026-07)
Progress0/23 (0%)

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.

text
β”Œβ”€β”€β”€β”€β”€β”
  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).

python
stack = []
# push β€” add to the top
stack.append(10)
stack.append(20)
stack.append(30)
print(stack) # [10, 20, 30]
# pop β€” remove from the top
top = stack.pop()
print(top) # 30 (the last element added)
print(stack) # [10, 20]
# peek β€” check the top element without removing it
print(stack[-1]) # 20

Where Stacks Are Used

Use CaseDescription
Undo (Ctrl+Z)Undo the last action first
Browser BackGo back to the last visited page
Function Call StackReturn from the most recently called function first
Bracket ValidationCheck 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.

text
enqueue β†’  β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”  β†’ dequeue
             β”‚ 10 β”‚ 20 β”‚ 30 β”‚
             β””β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”˜
             front    rear

It'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).

python
from collections import deque
queue = deque()
# enqueue β€” add to the back
queue.append(10)
queue.append(20)
queue.append(30)
print(queue) # deque([10, 20, 30])
# dequeue β€” remove from the front
front = 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 CaseDescription
Printer QueuePrint documents in the order they were sent
Task SchedulingProcess tasks in the order they were requested
BFS (Breadth-First Search)Visit nodes starting from the nearest one
Message QueueEnsure the order of messages between servers

Stack vs Queue Comparison

FeatureStackQueue
PrincipleLIFO (Last In, First Out)FIFO (First In, First Out)
AnalogyStacking dishesStanding in line
Addpush (to the top)enqueue (to the back)
Removepop (from the top)dequeue (from the front)
Pythonlist.append() + list.pop()deque.append() + deque.popleft()

Practical Example: Bracket Validation (Using a Stack)

python
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("({[]})")) # True
print(is_valid_brackets("([)]")) # False
print(is_valid_brackets("((")) # False

When 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."


πŸ’¬ Questions & Comments

0 comments

You can post without signing in. Guest comments cannot be edited or deleted by their author.

0/2000

Loading...