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:
- push:
stack.append(x) - pop:
stack.pop()(no argument: it takes the last item) - peek:
stack[-1] - 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 eachpop(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))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)Mistakes and edge cases.
- popping an empty list raises
IndexError: pop from empty list, andstack[-1]on an empty list raisesIndexError: list index out of range: checkif 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
What does this print?
stack = [] stack.append("a") stack.append("b") stack.append("c") stack.pop() stack.append("d") print(stack.pop(), stack)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
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)
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)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
Fix the class
Stackso it is a real stack:push(x),pop()(gives back the newest item),peek(),is_empty()andlen().pop()andpeek()on an empty stack must raiseIndexError.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.