Summary - Stack
- Algorithms course
- Beginner
- Lesson 64/80
- 4 min
Push and pop items and print the result in a mini task.
Summary - Stack
In this group you learned what a stack is, push, pop, peek and is_empty. All operations are O(1).
Stack follows LIFO: last in first out. It is used in undo, call stack and parenthesis matching.
Practice Stack size
Write stack_size(stack). Return the number of elements. Print 3 with print(stack_size([10, 20, 30])).
Starter code
def stack_size(stack):
# SizeSample solution
def stack_size(stack):
# Size
return len(stack)
print(stack_size([10, 20, 30]))Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Summary - Stack: match the terms
| Term | Meaning |
|---|---|
push |
Add |
pop |
Remove |
peek |
Show top |
LIFO |
Last in first out |
2 Stack principle
Stack follows the ____ principle.
Stack follows the LIFO principle.
Explanation: LIFO is right.
3 How long do all stack operations take?
- O(n)
- O(1) Correct answer
- O(n^2)
- O(log n)
Explanation: All operations are O(1).