Stack
how it works
The idea in a few sentences and two pictures, then one run, moment by moment.
Think of a pile of plates. You put a number on the top, and you can take only the top one off. So the last one in is the first one out, LIFO for short. Its formal name is a stack, and a put and a take are usually called push and pop. A program keeps the pile in a row, its top at the end. A put writes after the last number, and a take removes the last. Each touches only the end, so each costs 1, however tall the pile, while the row has room. This page counts these puts and takes. The storyboard, the run drawn moment by moment below, puts on 3, 7 and 5, takes one, puts on 9, then takes two. The watch page counts each moment of a run as a step. A put is two moments, the number picked up, then set on, yet counts once among the puts and takes.
Stack, newest out. Puts and takes happen at the right end, the top. The heavy line is the bottom.
Out, in turn: 5, 9, 7.
- just put in
- just taken out
Stack, newest out. Puts and takes happen at the right end, the top. The heavy line is the bottom.
Out, in turn: 8, 2, 4, 5.
Queue, oldest out. Numbers join at the right end, the back, and leave from the left end, the front.
Out, in turn: 5, 2, 8, 4.
- just put in
- just taken out
step 2 of 13
Pick up 3 to put it on the pile.
what it remembers to know where it is
- doing operation
- 1
- on top
- not yet
- in the pile
- 0
Where it says not yet, nothing is held there at that moment.
step 3 of 13
Set 3 on the top. The pile now holds one number.
what it remembers to know where it is
- doing operation
- 1
- on top
- 3
- in the pile
- 1
step 7 of 13
Set 5 on the top. The pile now holds 3 numbers.
what it remembers to know where it is
- doing operation
- 3
- on top
- 5
- in the pile
- 3
step 8 of 13
Take the top number, 5, off the pile. 7 is now on top.
what it remembers to know where it is
- doing operation
- 4
- on top
- 7
- in the pile
- 2
step 10 of 13
Set 9 on the top. The pile now holds 3 numbers.
what it remembers to know where it is
- doing operation
- 5
- on top
- 9
- in the pile
- 3
step 11 of 13
Take the top number, 9, off the pile. 7 is now on top.
what it remembers to know where it is
- doing operation
- 6
- on top
- 7
- in the pile
- 2
step 12 of 13
Take the top number, 7, off the pile. 3 is now on top.
what it remembers to know where it is
- doing operation
- 7
- on top
- 3
- in the pile
- 1
step 13 of 13
Done. The pile holds one number.
what it remembers to know where it is
- doing operation
- not yet
- on top
- 3
- in the pile
- 1
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start with an empty pilePython line 7
- to put a number on, set it on the topPython lines 9 and 10
- to take one off, take the top numberPython lines 11 and 12
- an empty pile has nothing to takePython lines 11 and 13
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def stack(operations):
"""Run a list of operations on a pile kept in a row, its top at the end.
A number puts it on the top, and None takes the top one off. Returns
the pile that is left, bottom first. It never compares two numbers.
"""
pile = [] # an empty pile
for op in operations:
if op is not None: # put a number on
pile.append(op) # after the last number: the new top
elif pile: # take one off, if there is one
pile.pop() # the last number leaves, and comes back
# an empty pile has nothing to take, so None does nothing
return pile
how it scales
How the puts and takes grow, from ten numbers to a million, each number put on and then taken off.
Each step across or up is ten times the one before, a log-log plot. Smallest first, shuffled and biggest first all cost the same, puts and takes, so the three cases draw one line. It climbs one step up for each step across: 20 puts and takes at 10 numbers, 2,000,000 at a million. Ten times the numbers, ten times the puts and takes.
puts and takes, ten times more at each mark up
, n, ten times more at each mark to the right
- put on biggest first, down to 1solid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
- shuffled, every order as likelysolid where measured by running it; dashed where its formula carries it on to ten million
- put on smallest first, 1 to solid where measured by running it; dashed where its formula carries it on to ten million
| puts and takes | time | |
|---|---|---|
| 1,000 | 2,000 | about 2 microseconds |
| 100,000 | 200,000 | about 200 microseconds |
| 10,000,000 | 20,000,000 | about 20 milliseconds |
The puts and takes are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count a stack's puts and takes yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it puts n numbers on an
empty pile and takes them all off, and prints the puts and takes for 1 to
n in order, n down to 1, and the average over 20 shuffles of 1 to n. Each
put counts 1, and so does each take that gives a number back. The counts
are the same on any computer; only the time differs.
"""
import random
def stack(operations):
"""Run a list of operations on a pile kept in a row, its top at the end.
A number puts it on the top, and None takes the top one off. Returns
the pile that is left, bottom first. It never compares two numbers.
"""
pile = [] # an empty pile
for op in operations:
if op is not None: # put a number on
pile.append(op) # after the last number: the new top
elif pile: # take one off, if there is one
pile.pop() # the last number leaves, and comes back
# an empty pile has nothing to take, so None does nothing
return pile
def cheapest(n):
"""1 to n put on in order, then n takes."""
return list(range(1, n + 1)) + [None] * n
def count(operations):
"""How many puts and takes the pile makes: each put, and each take that gives a number back."""
puts = sum(1 for op in operations if op is not None)
left = stack(operations)
# every number put on is still on the pile, or came back once
return puts + (puts - len(left))
if __name__ == "__main__":
random.seed(1)
print(f"{'n':>8} {'in order':>10} {'n down to 1':>12} {'shuffled':>10}")
for n in [10, 100, 1000, 10000, 100000]:
row = list(range(1, n + 1))
shuffles = []
for _ in range(20):
random.shuffle(row)
shuffles.append(count(row + [None] * n))
down = list(range(n, 0, -1)) + [None] * n
print(f"{n:>8} {count(cheapest(n)):>10} {count(down):>12} {sum(shuffles) / 20:>10.1f}")
best, worst and average
Every order costs the same: puts and takes, at every . No put or take looks at which number it holds, or compares two, so the order cannot change the count. At 4 numbers, 8 is 2 times 4. Each case is exactly 2 times , so its ceiling and its floor are that same multiple: , as lines 5 to 9 of section 4's first question show.
A case is one kind of input, the thing the method is given, such as a row back to front, whatever its length. A bound says how fast that case's cost grows as the input gets longer.
The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.
| bestput on smallest first, 1 to | averageshuffled, every order as likely | worstput on biggest first, down to 1 | |
|---|---|---|---|
| puts and takes | , every order alike | , no more than the rest | |
| how the puts and takes grow in each case | |||
| tight, | |||
| ceiling, | |||
| floor, | |||
extra memory: one place beside the row, where the top is (a row that doubles also keeps spare room, as section 4 draws it)
Extra memory is the room it needs on top of the input itself, while it runs.
| order put on | puts | takes | puts and takes |
|---|---|---|---|
| 1, 2, 3, 4 | 4 | 4 | 8 |
| 4, 3, 2, 1 | 4 | 4 | 8 |
| 3, 1, 4, 2 | 4 | 4 | 8 |
| 2, 4, 1, 3 | 4 | 4 | 8 |
Stack, newest out. Puts and takes happen at the right end, the top. The heavy line is the bottom.
Out, in turn: 3, 7.
- just put in
- just taken out
where the formula comes from
Each count above, worked out line by line. Each reason names the line it uses, and each 'where does this come from?' box opens a fact from another page.
the move: count the puts
the line:Stack, newest out. Puts and takes happen at the right end, the top. The heavy line is the bottom.
Out, in turn: 1, 2, 3, 4.
- just put in
- just taken out
Biggest first. 4 puts, then 4 takes, each counting 1, 8 in all. why it is allowed: The concept page on what a structure promises counts a put so. A full row first copies its numbers, but those copies are counted apart, in the question on a growing row. puts count .
the move: count the takes
the line:why it is allowed: The job takes off only as many as it put on, so every take finds a number and gives it back. takes count .
guess it, thenthe move: add them
the line:why it is allowed: is the puts and takes of numbers put on, then taken off, biggest first. By lines 1 and 2. For 4, 4 + 4.
guess it, thenthe move: two lots of n
the line:why it is allowed: By line 3, and are two lots of . For 4, 8, as the picture counts.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 4. An equals gives a ceiling and a floor at once.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 5, with the fixed multiple 2.
guess it, thenthe move: a floor
the line:why it is allowed: By line 4 again.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 7, with the fixed multiple 2.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 6 and 8 bound by the same growth, .
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: the order is never read
the line:why it is allowed: Lines 1 and 2 of the first question count every put and every take as 1, whatever the numbers.
the move: add them
the line:why it is allowed: is the puts and takes on 1 to in order, put on, then taken off. By lines 1 and 2 of the first question, of each. For 4, 4 + 4.
guess it, thenthe move: two lots of n
the line:why it is allowed: The first question's formula, so its lines 5 to 9 give here too.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: every order costs the same
the line:why it is allowed: As in order, no put or take reads a number. The 6 orders of 1, 2 and 3 each cost 6.
the move: average them
the line:why it is allowed: is the puts and takes over every order of numbers, each as likely. Equal costs average to that cost, by line 4 of the first question, and its lines 5 to 9 give here too. For 3, the 6 orders cost 36, and 36 shared by 6 is 6.
guess it, then
try it on small rows: over every order of 4 numbers, the average is
the move: a full row doubles
the line:- held
- just put in
- copied into the new row, bracketed under it
- room to spare
Nine puts. The row doubles at puts 2, 3, 5 and 9, copying 1, 2, 4 and 8 numbers. why it is allowed: A put that finds the row full first copies every number into a new row with twice the room. Then it writes its own.
the move: price a doubling
the line:- held
- copied into the new row, bracketed under it
- just put in
- room to spare
Put 5 finds a row of 4 full. It copies each number to the same place in a row of 8, then writes 7. why it is allowed: The room starts at 1 and only doubles, so it runs 1, 2, 4, 8. A full row holds as many numbers as its room, and the next put copies them all. Put 5 finds 4 and copies 4.
guess it, thenthe move: the last room
the line:Doublings of 1 up to 16. 9 lies between 8 and 16, so is 16. why it is allowed: For 9, put 9 found the row full at 8 and doubled it to 16. So 8 is below 9, and 16 is at or above 9. In general, by line 2 the rooms run 1, 2, 4, and on, so is a power of 2. It holds all , so it is at least . It doubled from half of only when a put found that half full, so half of is below . This holds from 2 numbers on; at 1, nothing doubles.
guess it, thenthe move: add the copies
the line:why it is allowed: is the copies of puts. By lines 2 and 3, the doublings copy the rooms 1, 2, 4, and on, up to half of , the room before the last doubling. For 9, 1 + 2 + 4 + 8, and is 16.
guess it, thenthe move: add the doublings
the line:where does this come from?
question 1 of the page doubling and halving sumsAdd . What is the total? the move: name the sum
the line:why it is allowed: Let be the doubling sum up to . For as 3, it is 1 + 2 + 4 + 8.
the move: double both sides
the line:why it is allowed: Each term doubled is the next one along, and becomes . Doubling both sides keeps them equal. The plan: the two sums share all but their ends.
the move: take line 1 away
the line:why it is allowed: Take from both sides of line 2. On the right, write out as line 1 does.
the move: tidy the left side
the line:why it is allowed: Two lots of less one lot is one lot.
the move: cancel what both brackets share
the line:when n is 3 1 2 4 8 16 first bracket 2 4 8 16 second bracket 1 2 4 8 left over take away 1 16 Line 4 when is 3. The 2, 4 and 8 cancel, leaving 16 less 1, which is 15. why it is allowed: Every term from 2 to is in both brackets and cancels, leaving less 1.
the move: the terms before the last
the line:why it is allowed: The sum of line 5 stopping one term sooner: line 5 with for . For 3, it is 1 + 2 + 4. At as 0 no terms are left, adding to 0, and 2 to the power 0, less 1, is 0 too.
the move: tidy the power
the line:why it is allowed: One more than is . For 3, 1 + 2 + 4 is 7, one less than 8.
the move: read it
the line:why it is allowed: By lines 6 and 7, the terms before the last add to one less than it: the last outweighs them all. By line 5 the sum is under , twice the last.
why it is allowed: The box under this line shows a doubling sum from 1 is one less than the next doubling. In the box, is not the puts: it counts the doublings from 1 to the last term. For 9 puts it is 3, as 1 doubled 3 times is 8, half of . After half of comes . For 9, 15 is 16 less 1.
guess it, thenthe move: the room is under twice the numbers
the line:why it is allowed: By line 3, half of is below . Doubling both, is below . For 9, 8 is below 9, so 16 is below 18.
guess it, thenthe move: a ceiling
the line:why it is allowed: By lines 5 and 6, is less 1, and is below , so is at most . For 9, 15 is at most 17. That is under 2 copies a number; in Sebastian Bourges' books, 'Under two moves per item' (volume two, chapter 21; their moves are this page's copies).
guess it, thenthe move: add the puts' own writes
the line:why it is allowed: Each put also writes its own number, writes in all. Add to both sides; and make . For 9, 15 + 9 is 24, at most 26.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 8, with the fixed multiple 3.
guess it, thenthe move: share it out
the line:put copies and its write so far share so far 1 1 1 1 2 2 3 1.5 3 3 6 2 4 1 7 1.75 5 5 12 2.4 6 1 13 about 2.17 7 1 14 2 8 1 15 about 1.88 9 9 24 about 2.67 Each put's copies and its own write, added up as the puts come. The share never reaches 3. why it is allowed: Line 8 divided by shares the copies and writes over the puts. One put may copy many, as put 9 copies 8. For 9, 24 over 9.
guess it, thenthe move: under 3
the line:why it is allowed: Line 10 takes one over from 3, and one over is above 0, so the share is under 3. For 9, 24 over 9 is about 2.67.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: a put at the start
the line:Stack, top at the start: place 1, on the left. A put moves each number held one place along; a take moves each one back.
Moves in all: 6.
- just put in
- just taken out
- moved one place along
- moved one place back
Three numbers on, then off, with the top at place 1, on the left. Kept at the end, the same pile needs no moves. why it is allowed: The top is now place 1, so the new number needs place 1 free. Each of the numbers held moves one place along first.
the move: a take at the start
the line:why it is allowed: The top leaves place 1, and each of the numbers still held moves one place back to fill the gap.
guess it, thenthe move: add the moves
the line:why it is allowed: is the moves of puts, then takes. By line 1 the puts move 0, 1, up to . By line 2 the takes move , down to 0, the same sum. For 3, 6.
guess it, thenthe move: leave out the 0
the line:why it is allowed: Adding 0 changes nothing.
guess it, thenthe move: use the page on adding up
the line:where does this come from?
question 1 of the page adding up Fit two staircases of squares together. What shape do they make? the move: draw the sum as a staircase
the line:why it is allowed: Let be the sum of the whole numbers from 1 to . Draw it as a staircase, a column for each number: 1 square, then 2, and so on up to . For 5, columns of 1, 2, 3, 4 and 5 hold 15 squares.
the move: take two staircases
the line:why it is allowed: Two staircases hold twice the squares. Doubling both sides of line 1 keeps it true.
the move: fit them into a rectangle
the line:Blue stands, yellow hangs. Two staircases of 1 to 5 squares fill a rectangle 5 wide and 6 tall, 30 squares. So 1 + 2 + 3 + 4 + 5 is 5 times 6, halved, which is 15. why it is allowed: Stand one staircase with its tallest column on the left. Hang the other upside down from the top, its tallest column on the right, as in the picture. The first column holds standing and 1 hanging. Each column to the right, the standing one loses a square and the hanging one gains one. So every column holds , and the columns fill a rectangle wide and tall.
the move: halve both sides
the line:why it is allowed: Halving both sides of line 3 keeps it true and leaves one . For 5, half of 30 is 15.
why it is allowed: The box under this line adds 1 up to a last number with two staircases, that number times one more, halved. Here the last number is . For 3, 2 times 3, halved, is 3, and times 2 is 6, as line 3.
guess it, thenthe move: halve, then double
the line:why it is allowed: Halving, then doubling, changes nothing. For 3, 3 doubled is 6.
guess it, thenthe move: tidy
the line:why it is allowed: is . For 3, 2 times 3 is 6.
guess it, thenthe move: multiply out
the line:why it is allowed: lots of , less lots of 1. For 3, 9 less 3.
guess it, thenthe move: add the puts and takes
the line:why it is allowed: Each put still writes its number and each take gives one back, puts and takes, as with the top at the end. Add to both sides; and make . For 3, 6 + 6 is 12.
guess it, thenthe move: a ceiling
the line:why it is allowed: Line 8 takes away from . For 3, 6 is at most 9.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 10, with the fixed multiple 1.
guess it, thenthe move: a fact about n
the line:why it is allowed: is times half of , and half of is at least 1 from 2 on. For 3, 3 is at most 4.5.
guess it, thenthe move: a floor
the line:why it is allowed: Line 8 takes from . By line 12, is at most half of , so at least half is left. For 3, 9 less 3 is 6, at least 4.5.
guess it, thenthe move: read it as a bound
the line:why it is allowed: By line 13, with the fixed multiple one half, from 2 numbers on.
guess it, thenthe move: ceiling and floor together
the line:why it is allowed: Lines 11 and 14 bound by the same growth, .
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
count it yourself
Count every put and take as 9, 6, 5 and 2 go on, biggest first, then all four come off. Each dash in the input is a take.
| step | the row | what happens | put on | taken off | puts and takes |
|---|---|---|---|---|---|
| 1 | Start with an empty pile, and 8 operations to do. | 0 | 0 | 0 | |
| 2 | Pick up 9 to put it on the pile. | 0 | 0 | 0 | |
| 3 | 9 | Set 9 on the top. The pile now holds one number.9 | 1 | 0 | 1 |
| 4 | 9 | Pick up 6 to put it on the pile.9 | 1 | 0 | 1 |
| 5 | 9, 6 | Set 6 on the top. The pile now holds 2 numbers.9, 6 | 2 | 0 | 2 |
| 6 | 9, 6 | Pick up 5 to put it on the pile.9, 6 | 2 | 0 | 2 |
| 7 | 9, 6, 5 | Set 5 on the top. The pile now holds 3 numbers.9, 6, 5 | 3 | 0 | 3 |
| 8 | 9, 6, 5 | Pick up 2 to put it on the pile.9, 6, 5 | 3 | 0 | 3 |
| 9 | 9, 6, 5, 2 | Set 2 on the top. The pile now holds 4 numbers.9, 6, 5, 2 | 4 | 0 | 4 |
| 10 | 9, 6, 5 | Take the top number, 2, off the pile. 5 is now on top.9, 6, 5 | 4 | 1 | 5 |
| 11 | 9, 6 | Take the top number, 5, off the pile. 6 is now on top.9, 6 | 4 | 2 | 6 |
| 12 | 9 | Take the top number, 6, off the pile. 9 is now on top.9 | 4 | 3 | 7 |
| 13 | Take the top number, 9, off the pile. The pile is empty again. | 4 | 4 | 8 | |
| 14 | Done. The pile holds nothing. | 4 | 4 | 8 |
In all, 8 puts and takes. The formula from section 4, , gives at : the same.
where you meet it
Piles are everywhere in programs, often without the name.
Python's list as a pile
Python's list, its row of items, makes a pile: append puts on the end, and pop takes the end off and gives it back. The first table below asks a list called pile, one line at a time. On an empty list, pop stops with an error, IndexError, where this page's Python does nothing. CPython, the usual Python, gives a growing list room for 4, then 8, 16, 24 and 32. It doubles at first; a long list grows by about an eighth and a few places, so it grows more often than a doubling row.
source: the Python tutorial, Using Lists as Stacks (opens in a new tab); CPython's Objects/listobject.c, list_resize
the call stack
A function is a named piece of a program. When one starts another, a call, the program sets a frame on a pile: the call's own numbers and where to come back to. When the call ends, a return, its frame comes off. Python stops a pile of calls grown too tall: past 1,000 frames, unless you change the limit, it stops with an error called RecursionError.
source: Python's documentation, sys.getrecursionlimit (opens in a new tab) and RecursionError (opens in a new tab); CPython's Include/internal/pycore_ceval.h, Py_DEFAULT_RECURSION_LIMIT
brackets and undo
Sebastian Bourges' books check that brackets nest with a pile. Each opening bracket goes on, and each closing one must match the top and take it off. The second table below traces it. Undo works the same way: the last change made is the first one undone.
source: Sebastian Bourges, Algorithmic Thinking Without the Jargon, volume two, chapter 21, 'Stacks and queues'
| asked | answer | the list after |
|---|---|---|
| pile.append(4) | None | [4] |
| pile.append(7) | None | [4, 7] |
| pile.pop() | 7 | [4] |
| pile.pop() | 4 | [] |
| pile.pop() | IndexError | [] |
| stack([4, 7, None, None, None]) | [] | this page's Python on 4, 7, -, -, -: the last take does nothing |
| read | pile after | why |
|---|---|---|
| ( | ( | opens, so goes on |
| [ | ( [ | opens, so goes on |
| ] | ( | closes the top, so it comes off |
| ( | ( ( | opens, so goes on |
| ) | ( | closes the top, so it comes off |
| ) | empty | closes the top, so it comes off |
| the end | empty | nothing left open: they nest |
what is used instead
When you must find a number inside, a pile is the wrong choice: it answers only which comes next. In the books' words, 'Do not reach for either when you also need to search' (volume two, chapter 21), either being a stack or a queue. When the oldest must come first, as at a printer, use a queue.
how it compares
Three ways to keep a pile, side by side. Each puts numbers on, then takes them all off.
| way | a put | a take | all on then all off | extra memory | reach for it when |
|---|---|---|---|---|---|
| top at the row's end | counts 1; a full row first copies every number | counts 1 | puts and takes, and at most copies if the row doubles | spare room, if the row doubles | almost always |
| top at the row's start | moves each number held along, then counts 1 | counts 1, then moves each number still held back | puts, takes and moves | spare room, if the row doubles | never; the end makes the same puts and takes and no moves |
| a chain of places | counts 1 | counts 1 | puts and takes, no copies | a link beside each number | a put must never wait for a copy |
- top at the end,
- top at the start,