Sub topic 2
The stack as an abstract data type
This chapter assumes you can write Python classes, use lists and indexing, and read basic Big-O notation. It defines the stack by its contract. The next chapters cover the individual operations and the implementations.
What an abstract data type is
An abstract data type (ADT) describes a collection by what it does, not by how it stores data. The description lists the operations, what each returns, and what each promises. Code that uses the ADT depends only on this contract. The storage can change without breaking that code.
The stack contract
A stack is an ordered collection where only one end, called the top, can be reached. It supports four operations: push, pop, peek, and is_empty. The contract says:
popremoves and returns the item most recently pushed that has not yet been popped.peekreturns that same item without removing it.popandpeekon an empty stack are errors.- Nothing below the top is visible. There is no indexing, searching, or iteration over the middle.
One invariant ties these rules together. After push(x), a pop() returns x and leaves the stack as it was before the push. Any correct implementation must preserve this.
Interface and implementation
The interface is the set of operations. An implementation is a class that stores the data and fulfills those operations.
In Python, an abstract base class can express the interface. The function reverse_text below accepts any stack and uses only the contract.
from abc import ABC, abstractmethod
class AbstractStack(ABC):
@abstractmethod
def push(self, item): ...
@abstractmethod
def pop(self): ...
@abstractmethod
def peek(self): ...
@abstractmethod
def is_empty(self): ...
class ListStack(AbstractStack):
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 reverse_text(text, stack):
for ch in text:
stack.push(ch)
out = []
while not stack.is_empty():
out.append(stack.pop())
return "".join(out)
print(reverse_text("stack", ListStack())) # kcatsLater you can pass a linked-list stack to reverse_text without changing it.
What the contract fixes and what it leaves open
| Fixed by the ADT | Left to the implementation |
|---|---|
| Last-in, first-out order | Array or linked nodes |
| Which operations exist | Resizing strategy |
| Error on `pop` from an empty stack | Exact exception type and message |
| Only the top is accessible | Memory layout and speed constants |
Common errors
- Leaking the storage. If callers can reach
_itemsand index into the middle, the type is no longer a stack, and code that depends on that access breaks when the storage changes. - Inconsistent empty behavior. One implementation raises on an empty
popand another returnsNone. Callers cannot swap them safely. Pick one rule and apply it everywhere. - Choosing the wrong end of a list. Pushing with
insert(0, x)is correct but costs O(n) per call. The contract allows it, and the cost is the reason to avoid it.
Exercise
A teammate's stack returns None from pop() when empty, while yours raises IndexError. Why does this break the ADT's value, and what should you do?
Show answer
Code written against one stack cannot be swapped to the other, because None can also be a valid pushed item and callers handle the two cases differently. Agree on one empty-stack behavior, document it as part of the contract (raising an error is the usual choice), and make every implementation follow it.