CodeBlanks Logo Icon CodeBlanks

What is a stack?

A LIFO (last in first out) data structure.

What is a stack?

A stack is a data structure that works on the last-in-first-out (LIFO) principle. Elements are added and removed only from the top.

Adding to a stack is called push, removing is pop. Looking at the top is peek. All are O(1).

Push and pop

push(item) places an element on top of the stack. pop() removes and returns the top element. Both are O(1).

Popping an empty stack is an error. Therefore it is good practice to check is_empty() before pop.

Practice Push

Write stack_push(stack, item). Add item to stack, return stack. Print [5] with print(stack_push([], 5)).

Starter code

solution.py
def stack_push(stack, item):
    # Push

Sample solution

solution.py
def stack_push(stack, item):
    # Push
    stack.append(item)
    return stack
print(stack_push([], 5))

Expected output

[5]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which principle does a stack follow?

  • Random
  • LIFO
  • Sorted
  • FIFO Correct answer

Explanation: Stack follows LIFO.

2 Push

Question
Adding to a stack is called ____.
Answer
Adding to a stack is called push.

Explanation: push is right.

3 What is a stack: match the terms

Term Meaning
push Add
pop Remove
peek Show top
LIFO Last in first out

All lessons in Beginner