PYTHON
Implementing a Basic LIFO Stack Using Python Lists
Understand how to implement a Last-In, First-Out (LIFO) stack data structure efficiently in Python using built-in lists, perfect for managing function call orders or undo features.
class Stack:
def __init__(self):
self._items = []
def is_empty(self):
return len(self._items) == 0
def push(self, item):
self._items.append(item)
print(f"Pushed: {item}. Stack: {self._items}")
def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack")
item = self._items.pop()
print(f"Popped: {item}. Stack: {self._items}")
return item
def peek(self):
if self.is_empty():
raise IndexError("peek from empty stack")
return self._items[-1]
def size(self):
return len(self._items)
# Demonstrate the Stack
my_stack = Stack()
print(f"Is stack empty? {my_stack.is_empty()}")
my_stack.push(10)
my_stack.push(20)
my_stack.push(30)
print(f"Top element: {my_stack.peek()}")
print(f"Stack size: {my_stack.size()}")
popped_item = my_stack.pop()
print(f"Popped item: {popped_item}")
my_stack.push(40)
popped_item = my_stack.pop()
popped_item = my_stack.pop()
popped_item = my_stack.pop()
print(f"Is stack empty? {my_stack.is_empty()}")
try:
my_stack.pop()
except IndexError as e:
print(f"Error: {e}")
How it works: A stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle, meaning the last element added is the first one to be removed. Python lists are well-suited for implementing a stack because their `append()` method adds items to the end (top of the stack), and their `pop()` method, when called without an index, removes and returns the last item (top of the stack). This snippet provides a simple `Stack` class demonstrating these core LIFO operations: `push` (add an element), `pop` (remove the top element), `peek` (view the top element without removing it), `is_empty`, and `size`.