PYTHON
Implementing a Last-In, First-Out (LIFO) Stack
Learn to implement a basic LIFO stack using Python lists, demonstrating push, pop, and peek operations essential for managing data in specific order.
class Stack:
def __init__(self):
self._items = []
def is_empty(self):
return not bool(self._items)
def push(self, item):
self._items.append(item)
def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack")
return self._items.pop()
def peek(self):
if self.is_empty():
raise IndexError("peek from empty stack")
return self._items[-1]
def size(self):
return len(self._items)
# Example Usage:
my_stack = Stack()
my_stack.push(10)
my_stack.push(20)
my_stack.push(30)
print(f"Stack size: {my_stack.size()}") # Output: Stack size: 3
print(f"Top element: {my_stack.peek()}") # Output: Top element: 30
print(f"Popped: {my_stack.pop()}") # Output: Popped: 30
print(f"Stack size after pop: {my_stack.size()}") # Output: Stack size after pop: 2
How it works: This snippet demonstrates how to implement a Last-In, First-Out (LIFO) stack using Python's built-in list. The `push` operation uses `append()` to add elements to the end, while `pop()` removes and returns the last element, mirroring LIFO behavior. The `peek` method allows inspection of the top element without removing it. This basic structure is fundamental for understanding recursion, expression parsing, and managing function call contexts.