Sub topic 1
Why a Stack Fits Undo
Prerequisites
This chapter assumes you know the following:
- Basic Python, including functions, classes, and lists.
- What a stack is, and what push and pop do.
- Basic string slicing such as
text[:5].
You do not need to know anything about undo and redo internals. This chapter covers only the first idea: why a stack is the right structure for remembering what to undo.
What undo has to do
Every editor that offers undo follows the same rule. Pressing undo reverses the most recent action. Pressing it again reverses the one before that, and so on back to the start.
That rule has two requirements:
- The program must remember actions in the order they happened.
- The program must reach the newest action first, without searching for it.
A stack meets both. It is a collection where you add and remove at one end only. The last item added is the first item removed. This is called last-in, first-out, or LIFO.
Push on action, pop on undo
Map the stack operations onto editing:
- When the user does something, push a record of it onto the stack.
- When the user presses undo, pop the top record and reverse it.
The diagram shows three actions and one undo.
After the third push the stack holds A at the bottom, B in the middle, and "delete line" on top. Undo takes from the top, so the delete is reversed first. That is the order the user expects.
A minimal version
This program keeps only the names of actions. It does not reverse anything yet. It shows the stack behavior on its own.
actions = []
def perform(name):
actions.append(name)
print("did", name)
def undo():
if not actions:
print("nothing to undo")
return
name = actions.pop()
print("undid", name)
perform("type A")
perform("type B")
perform("delete line")
undo()
undo()
undo()
undo()The output is:
did type A
did type B
did delete line
undid delete line
undid type B
undid type A
nothing to undoThe actions come back in the reverse of the order they went in. The fourth undo() finds an empty list. The if not actions check handles that case, so the program prints a message instead of raising an IndexError. A later chapter treats empty stacks in detail.
A Python list works as a stack because append and pop both work on the end of the list, and both take constant time on average.
Why the order matters
Undoing in the wrong order is not just surprising. It can corrupt the document, because each action was applied to the state left by the previous one.
Here is a text example. The user inserts "Hello" at position 0, then inserts " world" at position 5. The second insert is only valid because the first one made the text five characters long.
text = ""
# Action 1: insert "Hello" at position 0
text = text[:0] + "Hello" + text[0:]
# Action 2: insert " world" at position 5
text = text[:5] + " world" + text[5:]
print(text) # Hello world
# Correct undo order: reverse action 2 first
text = text[:5] + text[11:]
print(text) # Hello
# Then reverse action 1
text = text[:0] + text[5:]
print(text) # (empty string)If you reversed action 1 first, you would remove "Hello" and leave " world". Action 2's recorded position of 5 would then point past the end of a six-character string. A stack prevents this by construction, because an action can only be reversed when every later action has already been reversed.
Why not other structures
| Structure | Problem for undo |
|---|---|
| Queue (first-in, first-out) | Gives you the oldest action first, which is the opposite of what undo needs. |
| List with an index you search | Works, but you must track which entry is newest. A stack makes that the definition. |
| Set or dictionary | Has no order, so you cannot tell which action was last. |
Common errors
- Popping from the front with
pop(0). This removes the oldest action, so undo behaves like a queue. It is also slower, because every remaining item shifts. - Forgetting the empty check. Calling
pop()on an empty list raises anIndexError. - Removing the record without reversing the effect. Popping only updates the history. The document does not change unless you also run the reverse logic.
Exercise
A user performs actions in this order: A, B, C, then presses undo twice. Which actions have been undone, and which action is now on top of the stack?
Show answer
C was undone first, then B. Only A remains, so A is on top of the stack. Undo always pops the most recently pushed action that has not yet been undone.
Exercise
Why would using actions.pop(0) instead of actions.pop() break undo?
Show answer
pop(0) removes the oldest action, so undo would reverse the first action ever performed instead of the latest one. That later actions depend on earlier ones makes this wrong, and the document could end up in an invalid state.