PYTHON
Implementing a Basic LIFO Stack using a Python List
Understand how to implement a Last-In, First-Out (LIFO) stack using Python's built-in list methods, essential for managing ordered tasks.
class BasicStack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item) # Add to the end of the list
def pop(self):
if not self.is_empty():
return self._items.pop() # Remove from the end of the list
raise IndexError("pop from empty stack")
def peek(self):
if not self.is_empty():
return self._items[-1] # View the last item
raise IndexError("peek from empty stack")
def is_empty(self):
return len(self._items) == 0
def size(self):
return len(self._items)
# Example usage:
my_stack = BasicStack()
my_stack.push(10)
my_stack.push(20)
my_stack.push(30)
print(f"Stack size: {my_stack.size()}") # Output: 3
print(f"Top item (peek): {my_stack.peek()}") # Output: 30
print(f"Popped item: {my_stack.pop()}") # Output: 30
print(f"Popped item: {my_stack.pop()}") # Output: 20
print(f"Is stack empty? {my_stack.is_empty()}") # Output: False
my_stack.push(40)
print(f"Top item after push: {my_stack.peek()}") # Output: 40
my_stack.pop()
my_stack.pop()
print(f"Is stack empty? {my_stack.is_empty()}") # Output: True
How it works: This snippet illustrates how to implement a fundamental Last-In, First-Out (LIFO) stack data structure using a standard Python list. The `push` method adds an element to the end of the list, `pop` removes and returns the last element, and `peek` allows viewing the top element without removing it. The `is_empty` and `size` methods provide utility for checking the stack's state. This simple implementation is efficient because `append()` and `pop()` operations on the end of a Python list have an average O(1) time complexity.