Stacks
class Stack:
def __init__(self):
self.items = [] # Initialize an empty list to use as the stack
def is_empty(self):
"""Check if the stack is empty."""
return not self.items
def push(self, item):
"""Add an item to the top of the stack."""
self.items.append(item)
def pop(self):
"""Remove and return the top item from the stack. Assumes the stack is not empty."""
if not self.is_empty():
return self.items.pop()
else:
return "Stack is empty"
def peek(self):
"""Return the top item from the stack without removing it. Assumes the stack is not empty."""
if not self.is_empty():
return self.items[-1]
else:
return "Stack is empty"
def size(self):
"""Return the number of items in the stack."""
return len(self.items)
# Create a stack instance
stack = Stack()
# Push items onto the stack
stack.push("A")
stack.push("B")
stack.push("C")
# Peek at the top item
print(f"Top item is: {stack.peek()}")
# Pop an item off the stack
print(f"Popped item: {stack.pop()}")
# Check the current size of the stack
print(f"Stack size after popping: {stack.size()}")Last updated
Was this helpful?