A data structure is a way of organising data so it can be used efficiently. The stack is one of the most important — and most intuitive. Picture a stack of plates: you add to the top, and you take from the top. That simple rule powers the 'undo' button, the back button in your browser, and how Python itself remembers function calls.
1Linear structures and the LIFO stack
Data structures are broadly linear (items in a sequence — lists, stacks, queues) or non-linear (items in a hierarchy or web — trees, graphs).
A stack is a linear structure that follows the LIFO rule — Last In, First Out. The last item you add is the first one you remove. There are only two main operations:
- Push — add an item to the top of the stack.
- Pop — remove and return the item from the top.
Two error conditions matter:
- Overflow — trying to push when the stack is full (only applies if the stack has a fixed maximum size).
- Underflow — trying to pop when the stack is empty.
- Linear structures sequence data (list, stack, queue); non-linear ones use hierarchies (tree, graph).
- A stack is LIFO — Last In, First Out. Operations: push (add to top), pop (remove from top).
- Overflow = push onto a full stack; Underflow = pop from an empty stack.
2See it work — the stack visualizer
Push a few values, then pop them, and watch the LIFO rule in action: whatever you pushed last always comes off first. Try to pop an empty stack to trigger an underflow, and keep pushing to hit an overflow.
- Items pile onto the top; the most recently pushed is always on top.
- Pop always removes the top (the last pushed) — that's LIFO.
- Popping an empty stack is underflow; pushing a full one is overflow.
3Implementing a stack with a Python list
Python's list already behaves like a stack: append() pushes onto the end (the top), and pop() removes from the end. So a list is our stack — we just use its right end as the top:
- Push:
stack.append(item) - Pop:
stack.pop()— but always check for underflow first. - Peek/Top:
stack[-1](the last element). - Is empty?
len(stack) == 0
The key safety step is checking for underflow before popping. Run the implementation below:
Click Run to execute.
- A Python list works as a stack:
append()= push,pop()= pop,stack[-1]= top. - Always check
len(stack) == 0before popping to avoid underflow. - Because both push and pop use the list's end, they are fast.
★ Project: a reverse-with-a-stack tool
Using the playground, build a stack program that:
- Pushes each character of a word onto a stack (loop over the string).
- Pops them all off into a new string — which reverses the word (thanks to LIFO).
- Adds a peek() function that returns stack[-1] without removing it.
- Adds an is_empty() function and uses it to guard pop() against underflow.
Ready for the chapter test?
Answer 5 questions. Score 60% or more to mark this chapter complete.
Start the test →💡 Log in to save your progress and earn the certificate.