Sub topic 4
Implementing a Stack with a Dynamic Array
This chapter assumes you know Python classes, list indexing, and basic Big-O notation. You have already seen the push, pop, peek, and is_empty operations. Here you build them on top of a Python list, which is a dynamic array.
Why the end of the list is the top
A dynamic array stores items in a contiguous block of memory and grows that block when it fills up. Adding or removing at the end touches only one slot. Adding or removing at the front forces every other item to shift by one position, which costs O(n).
So the stack's top should be the end of the list. Push becomes append, and pop becomes pop() with no index.
The implementation
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
def __len__(self):
return len(self._items)The list is stored in _items. The leading underscore signals that callers should not touch it. If they could, they could insert in the middle and break the LIFO rule.
Try it:
s = Stack()
s.push("a")
s.push("b")
s.push("c")
print(s.pop()) # c
print(s.peek()) # b
print(len(s)) # 2Why push is amortized O(1)
A list allocates spare capacity. Most appends write into a free slot and cost O(1). When the block is full, Python allocates a larger block and copies every item, which costs O(n). Because the new block grows by a proportional factor, these copies become rare. Averaged over many pushes, each push costs O(1). That average is called amortized cost.
A single push can still be slow. If you need a hard worst-case bound on every call, such as in a real-time system, the linked-list version in a later chapter gives O(1) every time.
Common errors
- Using
insert(0, x)andpop(0). This makes the front the top. Each call is O(n), so a loop of n pushes costs O(n²). - Skipping the empty check.
list.pop()on an empty list already raisesIndexError, but with the message "pop from empty list". The explicit check gives an error that names the stack. Forpeek, the check matters more, becauseself._items[-1]would raise a confusingIndexErroron its own. - Returning
Noneon an empty stack. IfNonecan be a valid item, the caller cannot tell an empty stack from a storedNone. Raising an exception avoids this. - Exposing
_items. Code that reads the list directly can iterate in the wrong order or modify it. Keep access through the methods.
Summary of costs
| Operation | Time | Note |
|---|---|---|
| push | O(1) amortized | Occasional resize costs O(n) |
| pop | O(1) | Removes last item |
| peek | O(1) | Reads last item |
| is_empty | O(1) | Checks list truthiness |
| len | O(1) | Python stores the length |
Exercise
A teammate writes push as self._items.insert(0, item) and pop as self._items.pop(0). The stack still follows LIFO. What is wrong with it, and what is the time cost of n pushes?
Show answer
Every insert at index 0 and pop at index 0 shifts all existing items, so each operation is O(n). Doing n pushes costs O(1 + 2 + ... + n), which is O(n²). Using the end of the list as the top makes each push amortized O(1), so n pushes cost O(n).
Exercise
Why does peek need its own empty check when pop could rely on list.pop() to raise?
Show answer
self._items[-1] on an empty list raises an IndexError with a generic message about the index. An explicit check lets you raise a clear message such as "peek at empty stack" and keeps the behavior consistent with pop.