PYTHON
Building a Stack (LIFO) with Python Lists
Learn to implement a basic Last-In-First-Out (LIFO) stack data structure using Python's built-in list methods like append() and pop().
# Initialize an empty stack
my_stack = []
# Push items onto the stack (append to the end)
my_stack.append("Task 1")
my_stack.append("Task 2")
my_stack.append("Task 3")
print(f"Stack after pushes: {my_stack}") # Output: Stack after pushes: ['Task 1', 'Task 2', 'Task 3']
# Check if the stack is empty
print(f"Is stack empty? {not bool(my_stack)}") # Output: Is stack empty? False
# Pop items from the stack (remove from the end)
last_task = my_stack.pop()
print(f"Popped: {last_task}") # Output: Popped: Task 3
print(f"Stack after first pop: {my_stack}") # Output: Stack after first pop: ['Task 1', 'Task 2']
second_last_task = my_stack.pop()
print(f"Popped: {second_last_task}") # Output: Popped: Task 2
# You can also peek at the top element without removing it
if my_stack: # Check if stack is not empty before peeking
top_element = my_stack[-1]
print(f"Top element (peek): {top_element}") # Output: Top element (peek): Task 1
my_stack.pop() # Pop the last item
print(f"Stack after all pops: {my_stack}") # Output: Stack after all pops: []
print(f"Is stack empty? {not bool(my_stack)}") # Output: Is stack empty? True
How it works: A stack is a Last-In-First-Out (LIFO) data structure where the last element added is the first one to be removed. Python's built-in list type can efficiently function as a stack. The `append()` method adds an item to the "top" (end) of the stack, and the `pop()` method removes and returns the item from the "top" (end). This simple implementation is useful for scenarios like managing function call order, parsing expressions, or implementing undo functionalities.