Stacks: last in, first out
A stack is last in, first out: items go in and come out at the same end; a Python list is a stack with append and pop at the end, both O(1), while putting the top at the front makes every push move all the items.
An editor's Undo, a browser's Back button, functions calling each other and returning one by one: they all follow one rule, the last in is the first out (LIFO). A structure that stores things that way is a stack. In Python you do not have to build one: a list is a stack. But put the top at the wrong end and 1000 pushes cost 499,500 extra element moves. This lesson shows the right way to write it and what each way costs.
One end in, same end out
A stack only lets you work at one end, the top; the other end is the bottom. Putting something in is push, taking it out is pop, and looking without taking is peek.
With a list as the stack, the end is the top: append(x) is push, pop() is pop, stack[-1] is peek.
stack (bottom is stack[0], top is stack[-1])
379 stack[-1]1stack = []2stack.append(3)3stack.append(7)4stack.append(9)5print(stack)6print(stack[-1])7print(stack.pop())8print(stack)9print(len(stack), not stack)
[3, 7, 9] 9 9 [3, 7] 2 False
not stack asks "is the stack empty?": an empty list is falsy, so on an empty stack it is True.
With a list as a stack, how do you look at the top without taking it off?
stack[-1] is the last item: you look without taking. stack[0] is the bottom; stack.pop() takes the top away. On an empty stack stack[-1] raises IndexError, so check if stack: first.Why the top goes at the end
A list is a row of cells next to each other in memory. Putting or taking at the end moves nothing else: O(1). Make the front the top instead, and insert(0, x) first has to shift every item one cell to the right to free index 0; pop(0) is the same, shifting everything left after it takes the first item.
Count the moves for 1000 pushes. What insert(pos, x) has to move is every item after position pos:
1def moves_for_insert(lst, pos):2 return len(lst) - pos # every item after pos shifts one cell right3 4n = 10005front = []6moves = 07for i in range(n):8 moves += moves_for_insert(front, 0)9 front.insert(0, i) # the front as the top10print("front as the top:", moves, "moves")11 12back = []13moves = 014for i in range(n):15 moves += moves_for_insert(back, len(back))16 back.insert(len(back), i) # this is append: the end as the top17print("end as the top:", moves, "moves")18print(front[0] == back[-1])
front as the top: 499500 moves end as the top: 0 moves True
The two stacks hold the same things (999 on top of both), and the costs differ by hundreds of thousands of moves: the front costs 0 + 1 + … + 999 = n(n − 1) / 2, which is O(n²); the end never moves anything.
| You want to | With a list | Cost |
|---|---|---|
| push | stack.append(x) | O(1) (amortized: now and then it grows) |
| pop | stack.pop() | O(1) |
| look at the top | stack[-1] | O(1) |
| is it empty | not stack | O(1) |
| in and out at the front (don't) | stack.insert(0, x), stack.pop(0) | O(n) |
Push 1 2 3, pop once, push 4, then pop twice. What does it print?
1s = []2for x in [1, 2, 3]:3 s.append(x)4print(s.pop(), end=" ")5s.append(4)6print(s.pop(), s.pop(), end=" ")7print(s)
[1, 2]; pushing 4 makes it [1, 2, 4]; two more pops give 4 and 2, leaving [1]. Each pop takes the top at that moment, not the oldest item.Using the front of a list as the top, you push n times with insert(0, x). How many times do items move in total?
A Stack class
A bare list can do everything, including the wrong things: stack[0] and stack.insert(1, x) raise no errors. Wrap it in a class that keeps only a stack's operations, and nobody using it can get it wrong; popping an empty stack can also give an error that says what happened.
1class Stack:2 def __init__(self):3 self.items = []4 5 def push(self, x):6 self.items.append(x)7 8 def pop(self):9 if not self.items:10 raise IndexError("pop from empty stack")11 return self.items.pop()12 13 def peek(self):14 if not self.items:15 raise IndexError("peek from empty stack")16 return self.items[-1]17 18 def empty(self):19 return not self.items20 21 def __len__(self):22 return len(self.items)23 24s = Stack()25for x in [3, 7, 9]:26 s.push(x)27print(len(s), s.peek())28while s:29 print(s.pop(), end=" ")30print()31print(s.empty())32try:33 s.pop()34except IndexError as e:35 print("error:", e)
3 9 9 7 3 True error: pop from empty stack
With __len__ written, len(s) works, and so does while s:: when Python asks whether an object is true and it has no __bool__, it checks whether __len__ is 0.
| Method | Does | On an empty stack |
|---|---|---|
push(x) | puts x on top | works |
pop() | takes the top off and returns it | IndexError |
peek() | returns the top, leaves it there | IndexError |
empty() | is it empty | returns True |
len(s) | how many | 0 |
Push 1 2 3, then pop once. What does this print?
1class Stack:2 def __init__(self):3 self.items = []4 5 def push(self, x):6 self.items.append(x)7 8 def pop(self):9 return self.items.pop()10 11 def peek(self):12 return self.items[-1]13 14 def __len__(self):15 return len(self.items)16 17s = Stack()18for x in [1, 2, 3]:19 s.push(x)20s.pop()21print(len(s), bool(s), s.peek())
[1, 2]: len(s) is 2. bool(s) finds no __bool__, so it looks at __len__; 2 is not 0, so it is True. The top is 2.Write a Stack class
✓Fill in push, pop, peek and __len__, using the end of the list as the top.
3 c c b 1 a
1class Stack:2 def __init__(self):3 self.items = []4 5 def push(self, x):6 pass # put it at the end7 8 def pop(self):9 return None # take the last one off and return it10 11 def peek(self):12 return None # return the last one, leave it there13 14 def __len__(self):15 return 016 17s = Stack()18for ch in "abc":19 s.push(ch)20print(len(s), s.peek())21print(s.pop(), s.pop())22print(len(s), s.peek())
A min stack
✓get_min() scans with min() now, which is O(n). Make it O(1): keep a second stack mins, push "the smallest so far" onto it with every push, pop both stacks together, and let get_min() just read mins[-1].
2 [5, 3, 3, 2] 3 [5, 3, 3] 5 [5]
1class MinStack:2 def __init__(self):3 self.items = []4 self.mins = [] # mins[-1] is the smallest item on the stack now5 6 def push(self, x):7 self.items.append(x)8 9 def pop(self):10 return self.items.pop()11 12 def get_min(self):13 return min(self.items)14 15s = MinStack()16for x in [5, 3, 7, 2]:17 s.push(x)18print(s.get_min(), s.mins)19s.pop()20print(s.get_min(), s.mins)21s.pop()22s.pop()23print(s.get_min(), s.mins)
The call stack: the stack every program uses
Every function call you write is managed by a stack: calling a function pushes a frame onto the call stack, holding its arguments and local variables; when the function returns, its frame is popped and the return value goes to the frame below. The last call made is the first to return: last in, first out.
<module>print(total(3))total(3)n = 3total(2)n = 2total(1)n = 1total(0)n = 0The Traceback printed with an error is the call stack, bottom to top, at the moment it failed. Frames take memory, so the call stack has a limit (about 1000 levels by default in CPython). Recursion that never stops, or stops too late, runs into RecursionError:
1def total(n):2 if n == 0:3 return 04 return n + total(n - 1)5 6print(total(3))7print(total(100))8try:9 total(100000)10except RecursionError:11 print("RecursionError: the call stack cannot hold 100,000 levels")
6 5050 RecursionError: the call stack cannot hold 100,000 levels
Anything recursion does can be rewritten as a loop that keeps its own stack: a stack in a list can hold millions of items, with no call stack limit. Depth-first search on trees and graphs is written that way later on.
In interviews: "The costs of a list used as a stack", "Why not pop(0)?" and "What happens when recursion goes too deep, and how do you make it iterative?" come up often. The answers are this lesson: in and out at the end is O(1), at the front O(n); the call stack is itself a stack, and going iterative means keeping that stack yourself.
While working out total(3) (total(n) returns 0 when n is 0, otherwise n + total(n - 1)), what is the largest number of total frames on the call stack at the same time?
Pop orders
A favourite exam question: pushed in the order 1 2 3, which orders can they be popped in? Pushes and pops can be interleaved: push 1, pop, push 2, push 3, pop, pop gives 1 3 2.
stack
123Of the six orders, only one can't happen:
| Pop order | Possible? | How |
|---|---|---|
| 1 2 3 | yes | pop after each push |
| 1 3 2 | yes | push 1 pop, push 2 push 3, pop pop |
| 2 1 3 | yes | push 1 push 2, pop pop, push 3 pop |
| 2 3 1 | yes | push 1 push 2, pop, push 3, pop pop |
| 3 2 1 | yes | push everything, then pop everything |
| 3 1 2 | no | 3 out first means 1 and 2 are both still in, 2 above 1, so the next out can only be 2 |
The rule: when a number is popped, the ones pushed before it and not yet popped must come out in the reverse of the order they went in. n numbers have C(2n, n)/(n + 1) possible orders (the Catalan numbers), 5 for 3 numbers. This chapter's patterns lesson writes a program to decide.
The push order is 1 2 3 4. Which one can not be a pop order?
The push order is 1 2 3 4. How many different pop orders are possible?
How you write it at work
At work you almost never write a Stack class: use a list. stack = [], stack.append(x), stack.pop(), stack[-1], if stack:. An editor's undo, for example: before each change, push what the text looked like.
1text = ""2history = [] # the undo stack: the text before each change3for word in ["It ", "is ", "sunny"]:4 history.append(text)5 text += word6print(text)7text = history.pop() # undo once8print(text)9text = history.pop() # undo again10print(text)11print(len(history))
It is sunny It is It 1
collections.dequeworks as a stack too (append,pop), also O(1); but just as a stack, a list is simpler and its[i]indexing is faster.- For a stack shared by several threads, use the standard library's
queue.LifoQueue, which does its own locking. - As a type hint it is simply
stack: list[int] = []; no special type is needed.
Before each change to x, the old value goes on an undo stack. After undoing twice, what does this print?
1x = 02history = []3for step in [5, 3, 2]:4 history.append(x)5 x += step6x = history.pop()7x = history.pop()8print(x, history)
[0] is left. The last change is undone first: a stack.Summary
Stacks: in and out at the top, last in first out
- A list is a stack: the end is the top, and append and pop are both O(1)
- Never make the front the top: insert(0, x) and pop(0) move every item, O(n)
- A Stack class: push, pop, peek, empty, __len__; popping an empty one raises IndexError
- Function calls are a call stack: a call pushes a frame, return pops it; too deep is RecursionError
1stack = []2stack.append(x) # push3x = stack.pop() # pop4top = stack[-1] # peek5if not stack: ... # empty