PVM / Python / Data Structures / Stacks
1. Stacks Basics
A stack is a collection of items with restricted access.
You can only add items to the top.
You can only remove items from the top.
This rule is called LIFO (Last In, First Out).
You can't remove the middle item or inspect everything freely.
It is like a stack of plates.
It is like a browser back history.
It is like undo/redo in an editor.
Python does not have a special Stack type, but lists already support stack behavior.
append() -> push to top (end)
pop() -> remove from top (end)
py
undo_stack = []
undo_stack.append("Type Hello")
undo_stack.append("Type World")
undo_stack.append("Delete World")
print("Current stack:", undo_stack)
last_action = undo_stack.pop()
print("Undo action:", last_action)
print("Current stack:", undo_stack)
2. Custom Stack
Most languages do not provide stacks, but we can create one using list.
This is good for enforcing rules and readability.
With a raw list, this is posible:
stack = [1, 2, 3]
stack.insert(0, 99) - breaks stack rules
stack[1] = 42 - breaks stack rules
With a Stack class:
stack.push(1)
stack.push(2)
stack.push(3) - no way to touch the middle
py
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.items:
return None
return self.items.pop()
def peek(self):
if not self.items:
return None
return self.items[-1]
undo_stack = Stack()
undo_stack.push("Type: Hello")
undo_stack.push("Type: World")
undo_stack.push("Delete: World")
undo_stack.pop()
print("Top:", undo_stack.peek())
print("Stack:", undo_stack.items)
3. Collections Deque
Similar performance as custom stack implementation.
Deque is better for queues, but is also used as stack sometimes.
No custom class needed most of the time.
py
from collections import deque
MAX_HISTORY = 5
history = deque(maxlen=MAX_HISTORY)
history.append("google.com")
history.append("openai.com")
history.append("gitub.com")
history.append("python.org")
history.append("minte9.com")
print("History:", list(history))
history.append("stackoverflow.com")
print("History:", list(history))
last_page = history.pop()
print("Back to:", last_page)
print("History:", list(history))