Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Data Structures

Stacks: Last In, First Out, With the Undo Button

A stack is last in, first out: the newest thing you put on is the first thing you take off. Build Emma's undo button in Python from a list and one top index, push, pop and peek in one step each, undo after a million edits, and see what happens when you pop an empty stack.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Data Structures

What you will learn

  • Explain last in, first out with a stack of plates
  • Build a stack in Python from a list and one top index
  • Use push, pop and peek, and explain why each is O(1)
  • Guard against pop on an empty stack

Before you start

  • Python classes and lists
  • Arrays and dynamic arrays

A stack is last in, first out: the newest thing you put on is the first thing you take off. The undo button is the easiest way to see it.

The undo button

Emma is writing a note in a tiny editor. She types Hello, then she types Jack, then she makes it bold. The editor remembers every action, in order.

Now Emma presses undo. The first undo takes back make it bold. She presses it again, and it takes back type Jack. The newest action always goes first. A list that works like that is called a stack.

A stack of plates

Picture a stack of plates in the kitchen. You put down plate one, then plate two on top, then plate three. A new plate always goes on top. When you need a plate you take the top one, plate three: it went on last, so it comes off first. Pull out the bottom plate and the whole stack falls.

There are three words for this. Push means put a plate on top. Pop means take the top plate off. Peek means just look at the top plate without taking it. Only the top is ever touched. Last in, first out is LIFO for short.

Push three, pop two 432100 make it boldtype Jacktype Hellotype Hello top = 2 top = 0 pop, pop after three pushesafter two pops: size 1
The newest action sits on top, so it's the first one undone. Every move touches only the top cell.

Inside UndoStack

class UndoStack:
    def __init__(self, capacity):
        self.items = [None] * capacity
        self.top = -1  # -1 means the stack is empty

    def push(self, action):
        self.top += 1
        self.items[self.top] = action

    def pop(self):
        if self.top < 0:
            raise IndexError("pop from empty stack")
        action = self.items[self.top]
        self.items[self.top] = None
        self.top -= 1
        return action

    def peek(self):
        return self.items[self.top]

    def size(self):
        return self.top + 1

items is a list of cells, and top is one index. It starts at -1, which means the stack is empty. push moves top up by one and puts the action in that cell. pop reads the top cell, clears it with None, moves top down by one and returns the action. peek reads the top cell and changes nothing. size is simply top + 1.

There's no loop anywhere. Every method touches just one cell, the top.

Emma presses undo

from undo_stack import UndoStack

undo = UndoStack(5)
undo.push("type Hello")
undo.push("type Jack")
undo.push("make it bold")
print("Last action: " + undo.peek())

print("Undo: " + undo.pop())
print("Undo: " + undo.pop())  # again
print("Last action: " + undo.peek())
print("Actions left: " + str(undo.size()))
Last action: make it bold
Undo: make it bold
Undo: type Jack
Last action: type Hello
Actions left: 1

Play it. Five empty cells and top is -1. Push type Hello: top goes to 0 and the action goes in cell 0. Type Jack goes in cell 1, make it bold in cell 2. Peek only looks at cell 2. Pop reads cell 2, clears it, and top drops to 1. Undone. Pop again takes type Jack off, and top drops to 0. Peek now shows type Hello, the first thing Emma typed, and size is 0 + 1 = 1.

Make it bold went on last, so it came off first.

A million edits

from undo_stack import UndoStack

for n in (100, 10_000, 1_000_000):
    undo = UndoStack(n)
    for i in range(1, n + 1):
        undo.push("edit " + str(i))
    top = undo.size() - 1
    last = undo.pop()
    print(f"{n:9,d} edits: undo reads cell {top:,}: {last}")
      100 edits: undo reads cell 99: edit 100
   10,000 edits: undo reads cell 9,999: edit 10000
1,000,000 edits: undo reads cell 999,999: edit 1000000

With a million edits, undo reads cell 999,999 and that's it. It doesn't walk through a million cells; it jumps straight to the top. A short stack or a tower of a million plates, the hand reaches the top in one step.

Nothing to undo

Now break it. Emma presses undo before she types anything:

from undo_stack import UndoStack

undo = UndoStack(5)
print("Actions left: " + str(undo.size()))
print("Undo: " + undo.pop())  # nothing to undo
Actions left: 0
Traceback (most recent call last):
  ...
IndexError: pop from empty stack

(The middle of the traceback, with the file paths, is trimmed.) Top is -1, so there's no cell to read, and the program crashes. A real undo button checks that size is greater than zero first, and stays grey when there's nothing to undo.

One step, whatever the size

OperationCostWhat it touches
pushO(1)the cell above top
popO(1)the top cell (error if empty)
peekO(1)the top cell, read only
sizeO(1)top + 1

There's no loop over the stack, so the cost doesn't grow with it. In everyday Python, a plain list's append and pop() already work as a stack, and collections.deque does too.

Where you meet a stack

Undo in an editor takes back the newest change first. The back button in a browser returns to the page you opened last. When one function calls another, the caller waits, so the newest call finishes first; that's the call stack, and recursion leans on it. And a code editor checks brackets with a stack, because each closing bracket has to match the newest open one.

Recap

  • A stack is a pile where you only ever touch the top: last in, first out.
  • Push puts an item on top, pop takes the newest one off, peek looks without taking. Each is one step.
  • Popping an empty stack is an error, which is why the undo button goes grey.

Try it yourself: in undo_app.py, make a second UndoStack called redo, push every action you undo onto it, and print what redo.peek() gives you. Next, the opposite order: queues, first in, first out.

Keep going in Data Structures and Algorithms · 4 of 21

Previous
Linked Lists: A Chain of Clues, Built in Python
Next post
Queues: First In, First Out, With a Ring of Cells
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Related posts

What a Data Structure Is, and How Memory Works

Memory is a long row of numbered boxes, and opening any box is equally quick. A data structure is an agreed way of arranging things in those boxes, plus a few small notes. See with six songs on a phone why every structure is quick at some things and slow at others.

Arrays and Dynamic Arrays: Full? Get a Box Twice the Size

A fixed array never gets longer. A dynamic array fills its box, then copies everything into a box twice the size. Build one for Emma's playlist in Python, count the copies and shifts, and see why adding at the end stays cheap while inserting at the front costs almost 50 million shifts for 10,000 songs.

Linked Lists: A Chain of Clues, Built in Python

In a linked list every node holds a value and the address of the next node. Build a treasure hunt chain in Python: a new first clue is two moves at any size, slipping a clue in or out is just changing next, but reaching clue number i is a walk of i hops.

Queues: First In, First Out, With a Ring of Cells

A queue is first in, first out: whoever joins the line first is served first. Build Kate's cinema ticket line in Python as a ring of four cells, where nobody steps forward and only head and tail move, serve a million people with the same four cells, then break it with a line that is already full.

On this page

  • The undo button
  • A stack of plates
  • Inside UndoStack
  • Emma presses undo
  • A million edits
  • Nothing to undo
  • One step, whatever the size
  • Where you meet a stack
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.