Stacks and Queues in Python: A Complete Beginner’s Guide
#Stacks Queues in Python: A Complete Beginner’s Guide
Introduction
In Python, data structures like Stacks and Queues play an important role in solving real-world problems. Whether you’re preparing for coding interviews, building compilers, or working with task scheduling systems, these two structures are widely used.
In this tutorial, we’ll cover:
What is a Stack?
What is a Queue?
Their operations (push, pop, enqueue, dequeue)
Implementation in Python with examples
A Stack is a linear data structure that follows the LIFO (Last In, First Out) principle.
Think of a stack of plates — the last plate you put on top is the first one you take out.
Push → Add an element to the stack
Pop → Remove the top element
Peek/Top → View the top element without removing it
isEmpty → Check if stack is empty
stack = []
# Push
stack.append(10)
stack.append(20)
stack.append(30)
print("Stack:", stack)
# Pop
print("Popped:", stack.pop())
print("Stack after pop:", stack)
# Peek
print("Top element:", stack[-1])
✅ Output:
Stack: [10, 20, 30]
Popped: 30
Stack after pop: [10, 20]
Top element: 20
A Queue is a linear data structure that follows the FIFO (First In, First Out) principle.
Think of people standing in a line — the first person in line is the first to be served.
Enqueue → Add an element to the queue
Dequeue → Remove the front element
Peek/Front → Get the first element without removing it
isEmpty → Check if queue is empty
from collections import deque
queue = deque()
# Enqueue
queue.append(10)
queue.append(20)
queue.append(30)
print("Queue:", queue)
# Dequeue
print("Dequeued:", queue.popleft())
print("Queue after dequeue:", queue)
# Peek
print("Front element:", queue[0])
✅ Output:
Queue: deque([10, 20, 30])
Dequeued: 10
Queue after dequeue: deque([20, 30])
Front element: 20
queue
ModulePython also provides a built-in queue module for more advanced operations.
from queue import Queue
q = Queue()
# Enqueue
q.put(1)
q.put(2)
q.put(3)
# Dequeue
print("Dequeued:", q.get())
print("Dequeued:", q.get())
Feature | Stack (LIFO) | Queue (FIFO) |
---|---|---|
Order | Last In, First Out | First In, First Out |
Real-life Example | Stack of plates | People in a queue line |
Key Ops | Push, Pop | Enqueue, Dequeue |
Both Stacks and Queues are fundamental data structures in Python.
Use Stacks when you need LIFO operations (undo operations, function calls).
Use Queues when you need FIFO operations (task scheduling, message passing).
Mastering these concepts will help you write efficient code and ace coding interviews. 🚀
🔑 Target SEO Keywords:
stacks in Python, queues in Python, stack push pop Python, queue enqueue dequeue Python, Python data structures, Python collections deque, Python queue module