Stack Class

Stack Class

Write a Stack class — a last-in-first-out collection.

Stack()
  • __init__(self) — starts with an empty internal list.
  • push(self, item) — adds item to the top.
  • pop(self) — removes and returns the top item. If the stack is empty, raise IndexError("pop from empty stack").
  • peek(self) — returns the top item without removing it. If the stack is empty, raise IndexError("peek from empty stack").
  • is_empty(self) — returns True if there are no items.

Examples

s = Stack()
s.push(1)
s.push(2)
s.pop()    // → 2   (last one pushed, first one popped)

Stack().pop()   // raises IndexError("pop from empty stack")

Walkthrough

Thinking it through

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.items:
            raise IndexError("pop from empty stack")
        return self.items.pop()

    def peek(self):
        if not self.items:
            raise IndexError("peek from empty stack")
        return self.items[-1]

    def is_empty(self):
        return len(self.items) == 0

A stack is really just a Python list used in one particular way: additions and removals only ever happen at one end (the "top"). .append(item) adds to the end of the list, and the built-in list.pop() (no arguments) removes and returns the last element — put together, that's exactly last-in-first-out behavior, so push/pop are thin wrappers around list operations you already know.

peek is deliberately similar to pop, but reads self.items[-1] (the last element) instead of removing it — the two methods look almost identical, differing only in whether they mutate self.items.

Both pop and peek need the same empty-check guard, using the exceptions-section pattern of raising before attempting the operation: if not self.items: relies on the truthiness rule from way back in the conditionals lesson — an empty list is falsy, so not self.items is True exactly when there's nothing to pop or peek at.

This problem deliberately combines ideas from three different sections of this course — attributes and methods (OOP), raising a specific exception with a clear message (exceptions), and truthiness of an empty collection (conditionals) — which is exactly the kind of integration a real class in a real program requires.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.