CodeBlanks Logo Icon CodeBlanks

Undo stack

Push completed actions to an undo stack.

Undo stack

Now we write a function that pushes an action onto the stack. init_undo comes from the previous lesson and is used here.

The push operation: stack.append(action) adds the action to the end of the stack. Because of LIFO the last added stays on top and is undone first.

We can add several actions and watch the stack grow and its state; this tracks the undo history.

Action list

Actions are represented as strings: 'add', 'delete', 'change'. Each is pushed onto the stack and builds the undo history.

If several actions are added the stack grows. The last added is on top; it is undone first and removed from the history.

The stack size shows how many undos are possible; an empty stack means nothing to undo.

Practice Push action

Write push_undo(stack, action). Push onto stack, return stack. Print ['ekle', 'sil'] with s = init_undo(); push_undo(s, 'ekle'); push_undo(s, 'sil'); print(s).

Starter code

solution.py
def init_undo():
    # Empty undo stack
    return []
def push_undo(stack, action):
    # Push to undo stack

Sample solution

solution.py
def init_undo():
    # Empty undo stack
    return []
def push_undo(stack, action):
    # Push to undo stack
    stack.append(action)
    return stack
s = init_undo()
push_undo(s, 'add')
push_undo(s, 'del')
print(s)

Expected output

['ekle', 'sil']

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method does stack push use?

  • pop
  • insert
  • append Correct answer
  • remove

Explanation: append

2 Push return

Question
stack.append(action)
return ____
Answer
stack.append(action)
return stack

Explanation: stack is right.

3 Undo stack: match the terms

Term Meaning
append Push
pop Extract
LIFO Last first
Stack Undo

All lessons in Intermediate