PYTHON
Create an Immutable Stack with Tuples
Discover how to build a simple, immutable stack using Python tuples, ensuring data integrity by preventing in-place modifications for functional programming patterns.
def push(stack, item):
"""Returns a new stack with the item pushed onto the top."""
return stack + (item,)
def pop(stack):
"""Returns a tuple of (popped_item, new_stack) or (None, original_stack) if empty."""
if not stack:
return None, stack # Or raise IndexError
return stack[-1], stack[:-1]
def peek(stack):
"""Returns the top item without removing it, or None if empty."""
return stack[-1] if stack else None
def is_empty(stack):
"""Checks if the stack is empty."""
return not stack
# Usage
my_stack = () # Start with an empty tuple
print(f"Initial stack: {my_stack}")
my_stack = push(my_stack, 10)
my_stack = push(my_stack, 20)
my_stack = push(my_stack, 30)
print(f"Stack after pushes: {my_stack}")
top_item = peek(my_stack)
print(f"Peeked item: {top_item}")
item, my_stack = pop(my_stack)
print(f"Popped item: {item}, New stack: {my_stack}")
item, my_stack = pop(my_stack)
print(f"Popped item: {item}, New stack: {my_stack}")
print(f"Is stack empty? {is_empty(my_stack)}")
item, my_stack = pop(my_stack)
print(f"Popped item: {item}, New stack: {my_stack}")
print(f"Is stack empty? {is_empty(my_stack)}")
How it works: This snippet demonstrates an immutable stack implementation using Python tuples. Instead of modifying the stack in-place, `push` and `pop` operations return new tuple instances representing the updated stack. This approach ensures data integrity and is suitable for functional programming paradigms where state changes are avoided, making it easier to reason about data flow and prevent side effects.