PYTHON
Implement a Stack (LIFO) Using a Python List
Learn to implement a Last-In, First-Out (LIFO) stack data structure efficiently using Python's built-in list for managing data in web applications.
# A Python list can easily be used as a stack (LIFO - Last-In, First-Out)
# 'append()' to add items to the top of the stack (push)
# 'pop()' to remove items from the top of the stack (pop)
stack = []
# Push elements onto the stack
stack.append('Task 1')
stack.append('Task 2')
stack.append('Task 3')
print(f"Stack after pushing: {stack}")
# Pop elements from the stack (LIFO behavior)
last_task = stack.pop()
print(f"Popped: {last_task}, Stack: {stack}")
second_last_task = stack.pop()
print(f"Popped: {second_last_task}, Stack: {stack}")
# Try to pop from an empty stack (will raise IndexError)
# try:
# stack.pop()
# stack.pop()
# except IndexError:
# print("Attempted to pop from an empty stack.")
# Check if stack is empty
if not stack:
print("Stack is empty.")
stack.append('Task 4')
print(f"Stack after another push: {stack}")
How it works: Python's built-in `list` type can be efficiently used to implement a stack data structure, which follows a Last-In, First-Out (LIFO) principle. Items are added to the 'top' of the stack using `append()` (push operation) and removed from the 'top' using `pop()` (pop operation). The `append()` and `pop()` operations at the end of a list are highly efficient, making Python lists a natural choice for basic stack implementations, commonly used in scenarios like managing function call contexts, undo/redo mechanisms, or parsing expressions in web applications.