Model a stack, perform push and pop operations, and connect LIFO behaviour to undo, browser history and function-call execution.
01
Learning objectives
Define a stack and explain the Last In, First Out rule.
Trace push, pop, peek and is-empty operations.
Recognise stack overflow and underflow conditions.
Identify practical situations naturally modelled by stacks.
02
Lesson notes
A stack stores items in a sequence but restricts ordinary access to one end called the top. The most recently inserted item is removed first, so a stack follows Last In, First Out (LIFO). Think of a pile of plates: the top plate is the first one you can remove without disturbing the rest.
Push inserts an item at the top, pop removes and returns the top item, and peek reads the top without removing it. is_empty checks whether there are any items. Popping an empty stack causes underflow; pushing beyond a fixed-capacity implementation can cause overflow. The exact error policy depends on the implementation.
Stacks appear in undo and redo systems, navigation history, expression evaluation, bracket matching and the program call stack. When one function calls another, execution state is saved so the program can return to the correct location after the nested call finishes.
A Python list can implement a simple stack using append for push and pop for removal at the end. Operations at the end are efficient for this use. The interface matters more than the storage detail: a stack user should not depend on arbitrary access to middle elements.
03
Worked code examples
Worked example
The last pushed value is the first popped value, demonstrating LIFO behaviour.