PYTHON
Build a LIFO Stack with a Python List
Efficiently manage data using Last-In, First-Out (LIFO) behavior by leveraging Python's built-in list methods `append()` and `pop()` for stack operations.
# Initialize an empty stack
my_stack = []
# Push elements onto the stack (LIFO - Last In)
my_stack.append("Task A")
my_stack.append("Task B")
my_stack.append("Task C")
print(f"Stack after pushes: {my_stack}")
# Pop elements from the stack (LIFO - First Out)
if my_stack:
popped_item = my_stack.pop()
print(f"Popped: {popped_item}")
print(f"Stack after first pop: {my_stack}")
if my_stack:
popped_item = my_stack.pop()
print(f"Popped: {popped_item}")
print(f"Stack after second pop: {my_stack}")
# Check if stack is empty
if not my_stack:
print("Stack is empty.")
How it works: Python lists can be effectively used as a Last-In, First-Out (LIFO) stack. The `append()` method adds an item to the end of the list (the "top" of the stack), and the `pop()` method, when called without an index, removes and returns the last item added to the list. This straightforward approach provides a simple yet powerful way to manage ordered operations like function call stacks or undo mechanisms.