Python 3D Academyবাংলা

Last in, first out: push, pop and peek

🌍 In real life. At a wedding buffet the caterers put washed plates on a pile, one on top of another. Every guest takes the plate on top, so the plate that went on last is the first one used, and the one at the bottom waits longest. Nobody pulls a plate out from the middle: the pile would fall.

Your editor's Undo works the same way. Each change you make goes on a pile; Ctrl+Z takes back the most recent change first, then the one before it.

The idea in one sentence: a stack is a collection you only touch at one end, the top: the last item in is the first item out (LIFO, last in, first out).

Its words:

  • push: put an item on top
  • pop: take the top item off and give it back
  • peek (or top): look at the top item without taking it
  • empty: nothing on the stack; popping or peeking then is an error

How it works in Python, step by step: a list is a stack if you only use its end:

  1. push: stack.append(x)
  2. pop: stack.pop() (no argument: it takes the last item)
  3. peek: stack[-1]
  4. empty?: not stack

Watch three plates go on and come off, newest first:

Why it is correct. Every push and pop happens at the same end, so the top is always the most recent item still on the stack. Taking it off uncovers the one pushed just before it: exactly the order Undo needs.

Why the end of the list, and what it costs, worked out. A list keeps its items in a row of boxes (Chapter 34). At the end, append and pop() touch one box: O(1) (append now and then grows the list, but on average it is still one step). At the front, insert(0, x) and pop(0) move every other item one box over: O(n). For 10,000 pushes and pops:

  • at the end: about 20,000 steps
  • at the front: each insert(0, x) and each pop(0) moves everything already there, so the moves add up to about 10,000 × 10,000 = 100 million

Same stack, same answers, but one is thousands of times slower. Memory is O(n) either way: one box per item.

class Stack:
    def __init__(self):
        self.items = []

    def push(self, x):
        self.items.append(x)          # the end of the list is the top

    def pop(self):
        if not self.items:
            raise IndexError("pop from an empty stack")
        return self.items.pop()

    def peek(self):
        if not self.items:
            raise IndexError("peek at an empty stack")
        return self.items[-1]

    def __len__(self):
        return len(self.items)

plates = Stack()
for p in ["blue", "white", "red"]:
    plates.push(p)
print(plates.peek(), len(plates))
print(plates.pop(), plates.pop(), len(plates))
In everyday Python you rarely write this class: a plain list with append, pop() and [-1] is the stack. The class just gives the operations their stack names and clear errors.
text = ""
history = []                  # a stack of earlier versions
for word in ["Dhaka", " is", " busy"]:
    history.append(text)      # remember, then change
    text += word
print(text)
text = history.pop()          # Ctrl+Z
print(text)
text = history.pop()          # Ctrl+Z again
print(text)
Undo is a stack of earlier versions: each change pushes the old text, and each undo pops the most recent one.

Mistakes and edge cases.

  • popping an empty list raises IndexError: pop from empty list, and stack[-1] on an empty list raises IndexError: list index out of range: check if stack: first
  • pop(0) takes the oldest item: that is a queue, not a stack (and it is slow)
  • stack[0] is the bottom, not the top
  • printing a stack as a list shows the bottom first and the top last

Quiz

  1. What does this print?

    stack = []
    stack.append("a")
    stack.append("b")
    stack.append("c")
    stack.pop()
    stack.append("d")
    print(stack.pop(), stack)
  2. Plates 1, 2 and 3 are pushed in that order, then popped three times. In what order do they come off?

    • 3, 2, 1
    • 1, 2, 3
    • 2, 3, 1
  3. On a list of n items, what do stack.pop() and stack.pop(0) cost?

    • O(1) and O(n)
    • Both O(1)
    • O(n) and O(1)
  4. This stack gives back the oldest item instead of the newest. Which line is wrong?

    class Stack:
        def __init__(self):
            self.items = []
        def push(self, x):
            self.items.append(x)
        def pop(self):
            return self.items.pop(0)
  5. Two undos. What does this print?

    text = ""
    history = []
    for word in ["Hi", " there", "!"]:
        history.append(text)
        text += word
    text = history.pop()
    text = history.pop()
    print(text)

Coding tasks

  1. Fix the class Stack so it is a real stack: push(x), pop() (gives back the newest item), peek(), is_empty() and len(). pop() and peek() on an empty stack must raise IndexError.

  2. Write apply_edits(edits): each edit is a piece of text to type, or "<" to undo the most recent typing that hasn't been undone yet (an undo with nothing left to undo does nothing). Give back the final text.