17.1 What is a Stack?
You already use stacks every day without naming them. When you stack plates after dinner, the last plate you put on top is the first one you take off. When you press Undo in a text editor, the most recent change is the one that gets reversed first. When you press Back in a browser, you return to the page you visited most recently. Every one of these follows the same rule: last in, first out (LIFO).
A stack is the computer-science name for that rule. It is an Abstract Data Type — a "shape" for data plus the operations allowed on it. The clever part is that your programming language does not give you a ready-made stack, so you build one yourself out of an array plus an integer pointer.
| Term | Meaning |
|---|---|
| Stack | An ADT where items are added and removed at the same end (the top). LIFO. |
| LIFO | Last In, First Out — the last item added is the first removed. |
| Push | Add a new item to the top of the stack. |
| Pop | Remove and return the item from the top. |
| TopPointer | An integer holding the index of the current top item. Moves up on push, down on pop. |
| Overflow | Trying to push onto a full stack. A correct push must check for this. |
| Underflow | Trying to pop from an empty stack. A correct pop must check for this. |
| Peek | Look at the top item without removing it. The pointer does not move. |
- LIFO — last in, first out
- Only access the top (push/pop at one end)
- Use cases: Undo, Back button, expression evaluation
- LIFO, single-end access
- Browser Back button, or evaluating expressions
What is a Stack?
17.2 Setting Up the Stack
Python has no built-in "stack" type, so we build one from a list of a fixed size. We need three things:
- MAX_SIZE — a constant saying how many items the stack can hold.
- stack — the array (list) itself, sized to that constant.
- top_pointer — an integer that says which index currently holds the top item.
MAX_SIZE = 5 # the stack can hold 5 items
stack = [None] * MAX_SIZE # the array that stores the data
top_pointer = -1 # -1 means the stack is empty- With 0-based array indexing, an empty stack is shown by
top_pointer = -1. - When we push the first item it goes to index 0, and the pointer becomes 0.
- MAX_SIZE = 8
- Fill with "" (empty strings)
- top_pointer = -1
- Integers, so fill with 0 instead of ""
- Same three-line pattern
Setting Up the Stack
17.2B Interactive Simulator
Try the stack yourself. Set MAX_SIZE, enter a value, and click Push or Pop. Watch the top_pointer climb and fall, and try to trigger overflow and underflow. Use the playback controls to step through the code.
Stack
Status: Push or Pop to start.
Code
1MAX_SIZE = 52if top_pointer == MAX_SIZE - 1:3 print("Stack overflow")4 top_pointer = top_pointer + 15 stack[top_pointer] = new_item6if top_pointer == -1:7 print("Stack underflow")8 item = stack[top_pointer]9 top_pointer = top_pointer - 110 return item17.3 push() — Add to the Top
push() adds a new item to the top of the stack. The order is critical: check full → increment pointer → store item. Never store first then move the pointer, and never skip the full-check.
def push(new_item):
global top_pointer
if top_pointer == MAX_SIZE - 1: # is the stack full?
print("Stack overflow - cannot push")
else:
top_pointer = top_pointer + 1 # move the pointer up
stack[top_pointer] = new_item # store the item there- Check full → increment pointer → store item.
- Never store first then move the pointer, and never skip the full-check.
- Check if full: top_pointer == MAX_SIZE - 1
- If full: print message
- Else: increment, store
- Use global top_pointer
- Same shape — only the parameter name and message change
push() — Add to Top
17.4 pop() — Remove from the Top
pop() removes and returns the top item. The order is: check empty → read item → decrement pointer → return item. You must read the item BEFORE decrementing, or the pointer no longer points at it.
def pop():
global top_pointer
if top_pointer == -1: # is the stack empty?
print("Stack underflow - nothing to pop")
return None
else:
item = stack[top_pointer] # read the top item
top_pointer = top_pointer - 1 # move the pointer down
return item # give it back to the caller- Read
item = stack[top_pointer]FIRST, thentop_pointer -= 1, thenreturn item. - If you decrement first, the pointer no longer points at the item.
- Examiners give a mark for returning the popped value, not just removing it.
- A pop that only lowers the pointer "loses" the data.
- Read it into a variable before you decrement, then return that variable.
- Check if empty: top_pointer == -1
- If empty: return "Empty"
- Else: read item, decrement, return item
- Same as pop() — just a different name and empty message
pop() — Remove from Top
17.5 peek(), is_empty(), is_full()
These three tiny helpers make push and pop readable. Writing if is_full(): instead of if top_pointer == MAX_SIZE - 1: reads like English and is harder to get wrong.
def is_empty():
return top_pointer == -1
def is_full():
return top_pointer == MAX_SIZE - 1
def peek():
if is_empty():
return None
return stack[top_pointer]peek()returnsstack[top_pointer]without decrementing.- The item stays on the stack.
- Only
pop()moves the pointer.
- If top_pointer = 2, there are 3 items (indices 0, 1, 2)
- So size = top_pointer + 1
- Total slots minus items used
- MAX_SIZE - (top_pointer + 1)
peek(), is_empty(), is_full()
17.6 Tracing Push and Pop
A trace shows the stack state and top_pointer after each operation. Remember: push increments the pointer, pop decrements it.
# Trace: start empty, then push 7, push 3, pop, push 9
start top_pointer = -1 stack = []
push 7 top_pointer = 0 stack = [7]
push 3 top_pointer = 1 stack = [7, 3]
pop top_pointer = 0 (3 removed) -> returns 3
push 9 top_pointer = 1 stack = [7, 9]- Pointer up on push, down on pop
- push 4: tp=0 [4]
- push 8: tp=1 [4,8]
- push 2: tp=2 [4,8,2]
- pop: tp=1 (2 gone)
- pop: tp=0 (8 gone)
- push 5: tp=1 [4,5]
17.7 Full Exam-Style Question
A text editor keeps the last few text changes on a stack so the user can undo them. The most recent change must be undone first. The stack can hold up to 10 changes.
- The stack is stored as a global list
changeswith a global integertop. - Write program code to declare and initialise
changes,topand a constantMAXset to 10.
- Constant MAX = 10
- List of size MAX
- top = -1 (empty)
- Write a procedure
record(change)that adds a change to the stack. - If the stack is full it must output
"History full"and not add the change.
- Procedure header with parameter
- global top
- Full check: top == MAX - 1
- Output "History full" and do not add
- Else: increment top, store change
- Write a function
undo()that removes and returns the most recent change. - If there are no changes it returns
"Nothing to undo".
- Empty check: top == -1
- Return "Nothing to undo" if empty
- Read item before decrementing
- Decrement top, return item
Key Points Recap
✓ Key Points Summary
17.8 Practice Tasks
Fifteen exam-style stack tasks. Each shows only the question — click Hint for the thought process, or Help for the worked solution.
- For every stack task the marker checks:
- (1) correct overflow/underflow check
- (2) correct pointer movement (increment on push, decrement on pop — AFTER reading)
- (3) correct storage/retrieval, and (4) returning the popped value
- The most common mark loss is forgetting the full/empty check.
Question Bank
Answer all questions, then press Submit Quiz to see your score.
Question 1Multiple Choice
What rule does a stack follow?
Question 2True / False
TopPointer = -1 means the stack is empty.
Question 3Multiple Choice
What is the overflow condition?
Question 4Multiple Choice
What is the underflow condition?
Question 5True / False
In push(), you increment the pointer before storing the item.
Question 6Multiple Choice
In pop(), when do you read the item?
Question 7Multiple Choice
What does peek() do?
Question 8True / False
push() must declare "global top_pointer".
Question 9Multiple Choice
What does size() return?
Question 10Multiple Choice
Which is NOT a use case for a stack?
Question 11True / False
A stack is an Abstract Data Type (ADT).
Question 12Multiple Choice
What does spaces_left() return?
Answer all 12 questions to enable submission.