Push and pop
- Algorithms course
- Beginner
- Lesson 62/80
- 4 min
push adds, pop removes from a stack.
Pop operation
pop() removes and returns the top element. If the stack is empty, it raises an error. Therefore, check emptiness first.
Pop implements LIFO: the last element added is the first removed. This is useful for undo operations.
Peek and is empty
peek() shows the top element without removing it. is_empty() returns whether the stack is empty. Both are O(1).
Peek is used to look at the top without modifying the stack. is_empty is a safety check before pop.
Practice Pop
Write stack_pop(stack). Remove and return the top element. Print 7 with print(stack_pop([3, 7])).
Starter code
def stack_pop(stack):
# PopSample solution
def stack_pop(stack):
# Pop
return stack.pop()
print(stack_pop([3, 7]))Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Pop
Removing from a stack is done with ____.
Removing from a stack is done with pop.
Explanation: pop is right.
2 Push and pop: match the terms
| Term | Meaning |
|---|---|
pop |
Removes |
peek |
Shows |
is_empty |
Is empty |
append |
Adds |
3 Which element does pop remove?
- The first added
- The top one Correct answer
- The bottom one
- A random one
Explanation: It removes the top element.