Kodewick
Start learning →
Stacks: last in, first out13 / 52

Stacks: last in, first out

Lesson 13 of 52 · Part 3 · Stacks and queues · about 14 minutes

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])

append 3, 7 and 9, then pop once: out comes 9, the last one in, and no other item moves
main.py
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)
Output
[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.

Choose one

With a list as a stack, how do you look at the top without taking it off?

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.

stack3790123

The front as the top: insert(0, 1) first shifts 9, 7 and 3 one cell right to make room for 1

Count the moves for 1000 pushes. What insert(pos, x) has to move is every item after position pos:

main.py
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])
Output
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 toWith a listCost
pushstack.append(x)O(1) (amortized: now and then it grows)
popstack.pop()O(1)
look at the topstack[-1]O(1)
is it emptynot stackO(1)
in and out at the front (don't)stack.insert(0, x), stack.pop(0)O(n)
Guess the outputA wrong guess is fine

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)
Choose one

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.

main.py
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)
Output
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.

MethodDoesOn an empty stack
push(x)puts x on topworks
pop()takes the top off and returns itIndexError
peek()returns the top, leaves it thereIndexError
empty()is it emptyreturns True
len(s)how many0
Guess the outputA wrong guess is fine

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())
Exercise 1

Write a Stack class

Fill in push, pop, peek and __len__, using the end of the list as the top.

It should print
3 c
c b
1 a
exercise1.py
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())
Output
Press Run or Ctrl+Enter
Exercise 2

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].

It should print
2 [5, 3, 3, 2]
3 [5, 3, 3]
5 [5]
exercise2.py
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)
Output
Press Run or Ctrl+Enter

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) waits for total(2), which waits for total(1)… the top one finishes first and the answers are handed back down

The 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:

main.py
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")
Output
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.

Choose one

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

Pushing 1 2 3 with pops in between gives the pop order 1 3 2

Of the six orders, only one can't happen:

Pop orderPossible?How
1 2 3yespop after each push
1 3 2yespush 1 pop, push 2 push 3, pop pop
2 1 3yespush 1 push 2, pop pop, push 3 pop
2 3 1yespush 1 push 2, pop, push 3, pop pop
3 2 1yespush everything, then pop everything
3 1 2no3 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.

Choose one

The push order is 1 2 3 4. Which one can not be a pop order?

Choose one

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.

main.py
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))
Output
It is sunny
It is 
It 
1
  • collections.deque works 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.
Guess the outputA wrong guess is fine

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)

Summary

Take-away

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