Skip to the workspace
Pebellslearn by building
Linked Lists, Stacks & Queues  ›  Lesson

Stacks & Play History

Stacks 22 minLast in, first out: only the top is reachable

dsa / Stacks & Play History

Explore each scene at your own pace.

01 · Press back on Tunebox's play history

Press back on Tunebox's play history

Stacks & Play History

Definition
A stack is a collection that adds and removes items at one end only, so the last item added is always the first one removed (last in, first out); push adds, pop removes and peek looks at the top.
In plain words
Think of a pile of plates. You put a clean plate on top and you take the top plate off; you never pull one from the middle.

In short: a stack can only be touched at the top — push adds an item, pop removes the top item, and peek looks without removing. That one restriction gives LIFO: last in, first out. A Python list is already a stack as long as you only ever use its end — append/pop() are O(1), because the end is the free slot. It's the structure behind undo, matching brackets, evaluating expressions and even how function calls work.

A pile of plates: Intro, Verse, Chorus stacked bottom to top; a hand lifts only Chorus off the top, and an arrow shows Intro and Verse underneath are untouched

Press back on Tunebox's play history

python
What does this print?
stack = []
for track in ["A", "B", "C"]:
    stack.append(track)
stack.pop()
stack.append("D")
print(stack[-1], len(stack))

The mistake: pressing back with no history. Popping an empty list doesn't return None — it raises:

What happens when this runs?
history = ["Intro"]
history.pop()
print(history.pop())
python

❓ Cross-question — "Why the end of the list and not the front?" Because the end is free — append/pop() touch only the last slot: O(1). insert(0, x)/pop(0) shift every other item: O(n), the same cost from the linked-list lesson.

Scene 1 of 10
Project context and further resources
You're building a piece ofTunebox — the player
This piece — undo_history(): The back-button stack of what you played.
Scenario You play Intro, then Verse, then hit back. Tunebox's back button pops Verse off the history stack and leaves Intro on top.
undo_history.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
undo_history(actions) → listThe play-history stack after every action, oldest first.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.