Python Mastery – From Basics to Brilliance / Data Structures in Python

Stack and Queue

📚 Stack and Queue in Python

Stack and Queue are data structures used to store and manage data in a particular order.


🥞 Stack — LIFO

LIFO = Last In, First Out

The item added last is removed first.

Think of a stack of plates:

     ┌───────┐
     │   3   │ ← Last in → First out
     ├───────┤
     │   2   │
     ├───────┤
     │   1   │
     └───────┘

Using a List

stack = []

stack.append(10)
stack.append(20)
stack.append(30)

print(stack) #[10, 20, 30]

Remove the last item using pop():

stack.pop() #30

So:

Push → Add an item
Pop  → Remove the last item

Example Uses

  • ↩️ Undo/Redo

  • 🌐 Browser history

  • 🧮 Expression evaluation

  • 🔄 Function call stack


🚶 Queue — FIFO

FIFO = First In, First Out

The item added first is removed first.

Think of people standing in a queue:

First                Last
 ↓                    ↓
[10] → [20] → [30] → [40]
 ↓
Removed first

Python provides deque for efficient queues:

from collections import deque

queue = deque()

queue.append(10)
queue.append(20)
queue.append(30)

print(queue) #deque([10, 20, 30])

Remove the first item using popleft():

queue.popleft() #10

So:

Enqueue → Add an item
Dequeue → Remove the first item

Example Uses

  • 🖨️ Print queues

  • 🎫 Ticket systems

  • 💬 Task processing

  • 🌐 Network requests


⚖️ Stack vs Queue

Stack 🥞

Queue 🚶

LIFO

FIFO

Last In, First Out

First In, First Out

Add/remove from the same end

Add at one end, remove from the other

append() + pop()

append() + popleft()

Usually implemented using list

Usually implemented using deque