Medium: Interview Core · Problem 47 of 82

A Stack Class

MediumClassesPython

Write a class Stack that holds items last in, first out:

  • push(item) adds an item on top.
  • pop() removes and returns the top item; on an empty stack it raises IndexError.
  • peek() returns the top item without removing it; on an empty stack it raises IndexError.
  • len(stack) is the number of items, and bool(stack) is False for an empty stack.

Understand the problem

Revise the behaviour and the special methods.

After push(1), push(2), push(3) and one pop(), what is the next pop()?

  1. 3
  2. 2
  3. 1

Last in, first out: the first pop() returns 3, the next returns 2. A stack is like a pile of plates: you only touch the top.

Which special method makes len(stack) work, and also makes an empty stack falsy in an if?

  1. __len__
  2. __size__
  3. __count__

len() calls __len__. When a class has no __bool__ but has __len__, Python uses len(obj) != 0 for the truth value. One method gives both.

Write the solution

Write the class.

class Stack:
    # Write your code here.
    pass
Hint 1: a question to ask yourself

What built-in structure can hold the items and has an end that is cheap to add to and remove from?

Hint 2: the shape of the answer

Keep a list self._items. push is append, pop is the list pop() (which already raises IndexError when empty), peek is self._items[-1], __len__ is len(self._items).

Reflect

Solution

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 at empty stack")
        return self._items[-1]

    def __len__(self):
        return len(self._items)

What this tests: composition (the class has a list), a clean public interface, raising the right exception type, and __len__.

Why wrap a list instead of subclassing it: a Stack that inherits from list would also offer insert, sort and slicing, which break the idea of a stack. Wrapping exposes only the operations you intend.

Use the standard exceptions: IndexError for "nothing at that position", ValueError for "bad value", KeyError for "missing key". Callers already know how to handle them.

Why the list's end: append and pop() at the end are O(1). pop(0) at the front is O(n) because every item shifts. For a queue use collections.deque.

Cost: every operation is O(1).

What an interviewer might ask next: Use your stack to check whether brackets are balanced in "({[]})". (Push opening brackets, pop on closing ones, and compare.)