PYTHON
Implementing a Stack (LIFO) with Python Lists
Learn to implement a Last-In, First-Out (LIFO) stack data structure efficiently in Python using built-in list methods, ideal for managing function calls or parsing.
# Initialize an empty stack
my_stack = []
# Push elements onto the stack (append to the end)
my_stack.append('A')
my_stack.append('B')
my_stack.append('C')
print(f"Stack after pushes: {my_stack}")
# Pop elements from the stack (remove from the end)
if my_stack:
item_c = my_stack.pop()
print(f"Popped item: {item_c}")
print(f"Stack after first pop: {my_stack}")
if my_stack:
item_b = my_stack.pop()
print(f"Popped item: {item_b}")
print(f"Stack after second pop: {my_stack}")
# Check if the stack is empty
print(f"Is stack empty? {not bool(my_stack)}")
# Access the top element without removing it (peek)
if my_stack:
top_item = my_stack[-1]
print(f"Top item (peek): {top_item}")
my_stack.pop() # Pop 'A'
print(f"Stack after last pop: {my_stack}")
print(f"Is stack empty? {not bool(my_stack)}")
try:
empty_pop = my_stack.pop() # Attempt to pop from an empty stack
except IndexError as e:
print(f"Attempting to pop from an empty stack failed: {e}")
How it works: Python's built-in list can efficiently function as a stack (Last-In, First-Out). Elements are added to the 'top' of the stack using `append()`, and removed from the 'top' using `pop()`. This simple implementation is suitable for many use cases like managing function call order, parsing expressions, or backtracking algorithms, demonstrating basic stack operations without complex external libraries.