💡
Exercise 69

Stack Basics 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

A Stack is a Last-In-First-Out (LIFO) data structure — like a stack of plates! 🍽️

💡 Think of it like this: Imagine stacking plates. You always put new plates on TOP and take from the TOP. The last plate you put on is the first one you take off. That's LIFO!

# Python lists work perfectly as stacks! stack = [] stack.append(10) # Push: add to top stack.append(20) stack.append(30) print(stack[-1]) # Peek: look at top → 30 stack.pop() # Pop: remove from top → 30 # stack is now [10, 20]

Stack operations (all O(1)):

  • stack.append(x)Push: add element to the top
  • stack.pop()Pop: remove and return top element
  • stack[-1]Peek: look at top without removing
  • len(stack) == 0isEmpty: check if stack is empty

Where stacks appear everywhere:

  • ↩️ Undo/Redo: Ctrl+Z uses a stack (last action undone first)
  • 🌐 Browser history: Back button pops from the history stack
  • 🔤 Matching brackets: The classic stack interview problem
  • 📞 Function calls: Your computer uses a "call stack" to track function calls
  • 🧮 Expression evaluation: Calculators use stacks for order of operations
📋 Instructions
Practice using a stack. Push values 5, 10, 15, 20 onto a stack. Pop twice and print each popped value. Then print the top of the remaining stack using peek.
Use append() to push, pop() to remove from top, and stack[-1] to peek at the top without removing.
🧪 Test Cases
Input
stack.pop()
Expected
20
Test case 1
Input
stack.pop()
Expected
15
Test case 2
Input
stack[-1]
Expected
10
Test case 3
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.