Consider the following Python code that uses a list as a stack. What will be printed after the pop operation?
stack = [10, 20, 30, 40] popped = stack.pop() print(stack)
Remember, pop() removes the last item added to the list.
The pop() method removes the last element from the list, which is 40. So the remaining stack is [10, 20, 30].
What value is stored in popped after this code runs?
stack = ['a', 'b', 'c'] popped = stack.pop() print(popped)
Pop returns the last item removed from the stack.
The last item in the list is 'c', so pop() removes and returns 'c'.
What error will this code raise when executed?
stack = [] popped = stack.pop()
Think about what happens when you pop from an empty list.
Popping from an empty list raises an IndexError because there is no element to remove.
Given the stack [5, 10, 15, 20, 25], after performing pop() three times, how many items remain in the stack?
stack = [5, 10, 15, 20, 25] stack.pop() stack.pop() stack.pop() print(len(stack))
Each pop removes one item from the end.
Starting with 5 items, popping 3 removes 3 items, leaving 2 items.
Starting with an empty stack, perform these operations in order:
- push 1
- push 2
- pop
- push 3
- pop
- push 4
What is the final state of the stack?
stack = [] stack.append(1) stack.append(2) stack.pop() stack.append(3) stack.pop() stack.append(4) print(stack)
Track each operation step by step.
Operations:
push 1 → [1]
push 2 → [1, 2]
pop → removes 2 → [1]
push 3 → [1, 3]
pop → removes 3 → [1]
push 4 → [1, 4]