LearnWave
Learn it. Master it.

Stack

What a stack is

Describe a stack and give real-life and programming uses.

A data structure is a way of storing, organising and accessing data so that the operations we need are efficient. In a linear data structure, the elements are kept in a sequence, one after another; lists and strings are examples.

A stack is a linear data structure in which elements are added and removed at only one end, called the TOP. So the element added last is the one removed first: Last-In-First-Out (LIFO).

Stacks are everywhere in real life: a pile of plates in a kitchen (you take the top one, and put a washed one back on top), a pile of books or clothes, a stack of chairs, or bangles on a wrist.

And in programming:

  • Reversing a string: push each character, then pop them all; they come out in reverse order.
  • Undo/redo in a text editor: each change is pushed; undo pops the most recent one.
  • A web browser's BACK button: each page you visit is pushed onto a history stack, and BACK pops the latest. If you visit P1, then P2, then P3, pressing BACK twice takes you to P2 and then P1.
  • Checking that parentheses match in an expression.

Python has no separate stack (or queue) type, but these structures are used in many languages, and a Python list can easily act as one.

Last in, first out.
Last in, first out.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.