CodeBlanks Logo Icon CodeBlanks

Peek and is_empty

Peek the top without removing and check emptiness.

Peek and is empty

peek() shows the top element of the stack without removing it. is_empty() tells whether the stack is empty.

These two operations are important for safe stack use. is_empty before pop, peek before reading an element.

Stack use cases

Stack is used in undo operations, function call stack, parenthesis matching and DFS.

For example, undo in a text editor pushes each write to a stack and undo pops from it.

Practice Peek

Write stack_peek(stack). Return the top element without removing. Print 3 with print(stack_peek([1, 2, 3])).

Starter code

solution.py
def stack_peek(stack):
    # Peek

Sample solution

solution.py
def stack_peek(stack):
    # Peek
    return stack[-1]
print(stack_peek([1, 2, 3]))

Expected output

3

Questions and answers

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

1 Peek and is_empty: match the terms

Term Meaning
peek Show top
is_empty Is empty
undo Undo
call stack Functions

2 Where is a stack NOT used?

  • Undo
  • Parenthesis matching
  • Binary search Correct answer
  • DFS

Explanation: Binary search does not use a stack.

3 Peek

Question
Read the top element without removing with ____.
Answer
Read the top element without removing with peek.

Explanation: peek is right.

All lessons in Beginner