PYTHON
Implementing a LIFO Stack using Python Lists
Learn to implement a Last-In, First-Out (LIFO) stack data structure using Python's built-in list methods like append() and pop(), essential for managing call contexts or undo operations.
class SimpleStack:
def __init__(self):
self._items = [] # Internal list to hold stack elements
def is_empty(self) -> bool:
return not self._items
def push(self, item):
"""Adds an item to the top of the stack."""
self._items.append(item)
print(f"Pushed: {item}. Stack: {self._items}")
def pop(self):
"""Removes and returns the item from the top of the stack."""
if self.is_empty():
raise IndexError("Cannot pop from an empty stack.")
item = self._items.pop()
print(f"Popped: {item}. Stack: {self._items}")
return item
def peek(self):
"""Returns the item at the top of the stack without removing it."""
if self.is_empty():
raise IndexError("Cannot peek into an empty stack.")
return self._items[-1]
def size(self) -> int:
return len(self._items)
# Example usage in a web development context (e.g., managing routing history)
history_stack = SimpleStack()
history_stack.push("/dashboard")
history_stack.push("/users")
history_stack.push("/users/profile/123")
print(f"Current page (peek): {history_stack.peek()}")
print(f"Stack size: {history_stack.size()}")
# Simulate navigating back
history_stack.pop() # /users/profile/123
print(f"Navigated back to: {history_stack.peek()}") # /users
history_stack.pop() # /users
print(f"Navigated back to: {history_stack.peek()}") # /dashboard
try:
history_stack.pop() # /dashboard
history_stack.pop() # Should raise an error
except IndexError as e:
print(f"Error: {e}")
How it works: A stack is a Last-In, First-Out (LIFO) data structure. Python lists can efficiently implement a stack using their built-in append() method to add elements to the "top" (end of the list) and pop() (without an index) to remove elements from the "top" (end of the list). This snippet demonstrates how to encapsulate these operations within a SimpleStack class, making it clear and reusable. Stacks are fundamental in web applications for managing browser history, undo/redo functionalities, or handling function call contexts.