LearnWave
Learn it. Master it.

Stack

Stack operations in Python

Write stack functions using append() and pop().

A stack has two main operations:

  • PUSH: insert a new element at the TOP. Pushing onto a stack that is already full causes overflow.
  • POP: remove the element at the TOP. Popping from an empty stack causes underflow.

In Python, a list makes a simple stack, with its right end as the TOP:

  • append(element) pushes an element onto the top;
  • pop() removes and returns the top element.

Because these work at the end of the list automatically, there is no need to keep a separate TOP variable. And since a list has no fixed size, overflow does not happen, unless the computer runs out of memory.

For example, starting with the stack [1, 2]: push 3 gives [1, 2, 3]; pop removes 3; another pop removes 2; the stack is left as [1].

The book builds a stack of glasses, glassStack, with a set of functions:

  • isEmpty(glassStack): returns True if the stack is empty, by checking whether its length is 0. It should be checked before popping, to avoid underflow.
  • opPush(glassStack, element): pushes with append().
  • opPop(glassStack): pops with pop(), after checking that the stack is not empty.
  • size(glassStack): returns the number of elements, using len().
  • top(glassStack): returns the top element, glassStack[len(glassStack)-1], without removing it.
  • display(glassStack): prints the elements from top to bottom.
append() to push, pop() to pop.

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.