Sub topic 3
Push, pop, peek, and is_empty
This chapter assumes you can write Python classes and know that a list supports append, pop, and indexing. It also assumes you know basic Big-O notation. You already know a stack removes the most recently added item first. Here you will pin down the four core operations and the contract each one follows.
The four operations
Every stack, whatever its storage, offers the same small interface.
| Operation | What it does | Returns | When the stack is empty |
|---|---|---|---|
| `push(item)` | Adds `item` to the top | Nothing | Always works |
| `pop()` | Removes the top item | The removed item | Error |
| `peek()` | Reads the top item | The top item | Error |
| `is_empty()` | Checks for any items | `True` or `False` | Returns `True` |
The key difference is between pop and peek. Both return the top item, but pop removes it and peek leaves the stack unchanged.
A worked trace
The sequence below shows how the stack changes. The top is the right end of each list.
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 is_empty(self):
return not self._items
s = Stack()
print(s.is_empty()) # True
s.push("a")
s.push("b")
s.push("c") # stack: a, b, c
print(s.peek()) # c
print(s.pop()) # c
print(s.pop()) # b
print(s.is_empty()) # False
print(s.pop()) # a
print(s.is_empty()) # TrueAfter three pushes, the items come back in the reverse order: c, b, a. This reversal is the visible effect of last in, first out.
Rules to remember
- Only the top is accessible. You cannot read or remove an item in the middle without first popping everything above it.
popandpeekon an empty stack are errors. The caller should not receive a made-up value such asNone, becauseNonecould be a legitimate item.is_emptylets the caller check first, so the error never occurs.
A common loop drains a stack safely:
s = Stack()
for word in ["one", "two", "three"]:
s.push(word)
while not s.is_empty():
print(s.pop()) # three, two, oneCommon mistakes
- Calling
popwhen you meantpeek. The item disappears and later code sees a smaller stack. - Forgetting to check
is_emptybeforepop, which raisesIndexErroron empty input. - Pushing a list with
appendbut then readingitems[0]. That is the bottom, not the top.
Exercise
A stack starts empty. You run push(1), push(2), pop(), push(3), peek(), pop(). What does each of pop() and peek() return, and what is left in the stack?
Show answer
The first pop() returns 2. peek() returns 3, and the final pop() returns 3. The stack then holds only 1.
Exercise
Why does pop() raise an error on an empty stack instead of returning None?
Show answer
None could be a real value that was pushed, so the caller could not tell an item from an empty stack. An error makes the mistake visible at once.