PYTHON
Implementing a Basic LIFO Stack with Python Lists
Learn to simulate a Last-In, First-Out (LIFO) stack using Python's built-in list methods `append()` for pushing elements onto the stack and `pop()` for retrieving them.
# Initialize an empty stack
my_stack = []
# Push elements onto the stack
my_stack.append('Task 1')
my_stack.append('Task 2')
my_stack.append('Task 3')
print(f"Stack after pushes: {my_stack}")
# Pop elements from the stack (LIFO)
if my_stack:
popped_item = my_stack.pop()
print(f"Popped item: {popped_item}")
print(f"Stack after first pop: {my_stack}")
if my_stack:
popped_item = my_stack.pop()
print(f"Popped item: {popped_item}")
print(f"Stack after second pop: {my_stack}")
# Check if stack is empty
if not my_stack:
print("Stack is now empty.")
How it works: Python lists can effectively function as LIFO (Last-In, First-Out) stacks. The `append()` method adds items to the 'top' of the stack, while the `pop()` method removes and returns the item most recently added (the last element). This simple pattern is useful for managing execution order, undo histories in applications, or parsing expressions.