Mastering Stacks in Python – The Badass Queen’s
Guide ■
A **stack** is a linear data structure that follows the **LIFO** (Last In, First Out) principle. Think of it like a
stack of plates: the last plate you put on top is the first one you take off. In Python, stacks can be
implemented in multiple ways, including **lists**, **[Link]**, and using **classes**.
**LIFO Principle:** - Last In → First Out - Imagine a stack of pancakes: the last pancake placed is the first
one eaten.
**Basic Stack Operations:** 1. **push(item)** → Add an item to the top of the stack. 2. **pop()** → Remove
and return the top item. 3. **peek()/top()** → View the top item without removing it. 4. **is_empty()** →
Check if the stack is empty. 5. **size()** → Return the number of elements in the stack.
1. Implementing Stack using Python List
# Stack implementation using list
stack = []
# Push elements
[Link](10)
[Link](20)
[Link](30)
print("Stack after pushes:", stack)
# Pop element
print("Popped element:", [Link]())
# Peek top element
print("Top element:", stack[-1])
# Check if stack is empty
print("Is stack empty?", len(stack) == 0)
Here, `append()` acts as **push** and `pop()` removes the top element. Accessing `stack[-1]` lets us peek
at the top item.
2. Implementing Stack using a Class (OOP Way)
class Stack:
def __init__(self):
[Link] = []
def push(self, item):
[Link](item)
print(f"Pushed {item} → Stack: {[Link]}")
def pop(self):
if not self.is_empty():
removed = [Link]()
print(f"Popped {removed} → Stack: {[Link]}")
return removed
else:
print("Stack is empty!")
return None
def peek(self):
if not self.is_empty():
return [Link][-1]
return None
def is_empty(self):
return len([Link]) == 0
def size(self):
return len([Link])
# Example usage
s = Stack()
[Link](5)
[Link](15)
print("Top element:", [Link]())
[Link]()
print("Is stack empty?", s.is_empty())
This **OOP approach** is cleaner and encapsulates stack behavior inside a class. Each operation is clearly
defined, making it more maintainable.
3. Implementing Stack using [Link] (Faster)
from collections import deque
stack = deque()
[Link]('A')
[Link]('B')
[Link]('C')
print("Stack:", stack)
print("Popped:", [Link]())
print("Peek:", stack[-1])
`deque` (double-ended queue) from `collections` is **faster** for stack operations than lists, especially for
large data, because it has optimized append and pop operations.
4. Real-World Example – Undo Feature Simulation
class UndoStack:
def __init__(self):
[Link] = []
def do_action(self, action):
[Link](action)
print(f"Action performed: {action} → History: {[Link]}")
def undo(self):
if [Link]:
undone = [Link]()
print(f"Undo: {undone} → Remaining: {[Link]}")
else:
print("Nothing to undo.")
# Example usage
u = UndoStack()
u.do_action("Type 'Hello'")
u.do_action("Delete 'o'")
[Link]()
This simulates a **text editor undo feature** using a stack. Each action is pushed, and when undo is
triggered, the last action is popped.