Final answer:
A simple Python program to demonstrate a stack data structure for managing to-do list items, as well as essential stack operations such as push, pop, peek, and checking if the stack is empty.
Step-by-step explanation:
If you are building a web application that manages to-do lists using a stack data structure, here's a Python program to handle the operations as described:
- Create an empty stack for to-do items.
- Push a new item onto the stack.
- Print all items in the stack.
- Print the top item of the stack.
- Pop an item from the stack.
- Check and print the size of the stack.
- Check if the stack is empty.
- Pop another item from the stack.
- Print the remaining items in the stack.
Here's how you would implement it:
stack = [] # Creates an empty stack
def push(item):
stack.append(item) # Adds an item
def print_stack():
print(stack) # Prints all items
def peek():
if stack:
print(stack[-1]) # Prints the top item
def pop_item():
if stack:
return stack.pop() # Removes the top item
else:
print("Stack is Empty")
def stack_size():
return len(stack) # Returns the size of the stack
def is_empty():
return len(stack) == 0 # Checks if stack is emptypush("Buy groceries")
push("Do laundry")
push("Pay bills")
print_stack()
peek()
print(f"Popped item: {pop_item()}")
print(f"Stack size: {stack_size()}")
print("Stack is Empty" if is_empty() else "Stack is not Empty")
print(f"Popped item: {pop_item()}")
print_stack()
This program demonstrates basic stack operations following a last in, first out (LIFO) principle.