PYTHON
Implement a Basic Stack Data Structure using Python Lists
Understand how to implement a Last-In, First-Out (LIFO) stack using standard Python list methods like `append()` for push and `pop()` for retrieving items.
# Initialize an empty stack
stack = []
# Push elements onto the stack (append to the end of the list)
stack.append('A')
stack.append('B')
stack.append('C')
print(f"Stack after pushes: {stack}")
# Pop elements from the stack (remove from the end of the list)
popped_item = stack.pop()
print(f"Popped item: {popped_item}")
print(f"Stack after first pop: {stack}")
popped_item = stack.pop()
print(f"Popped item: {popped_item}")
print(f"Stack after second pop: {stack}")
# Check if the stack is empty
print(f"Is stack empty? {not bool(stack)}") # Or len(stack) == 0
# Attempting to pop from an empty stack will raise an IndexError
# try:
# stack.pop()
# stack.pop()
# except IndexError:
# print("Cannot pop from an empty stack!")
How it works: This snippet illustrates the implementation of a basic stack using a Python list. A stack is a Last-In, First-Out (LIFO) data structure. Elements are "pushed" onto the stack using the `append()` method, which adds them to the end of the list. Elements are "popped" from the stack using the `pop()` method, which removes and returns the last element added. This behavior perfectly mimics the LIFO principle, as `pop()` without an index argument removes the last element.