The following Python list S is being used as a stack with the top stored at…
2023
The following Python list S is being used as a stack with the top stored at the leftmost position (index 0): S = [10, 12, 0, 4, 6]. If 10 was pushed last, which command should be used to pop the top element from stack S, if it is not empty?
- A.
S.pop(0)
- B.
S.pop()
- C.
S.remove()
- D.
S.remove(0)
Attempted by 1970 students.
Show answer & explanation
Correct answer: A
The list is being used as a stack, but the question explicitly defines this stack implementation with the top at the leftmost position, index 0. Since 10 was pushed last, 10 is the current top element. To pop the top element, we must remove the item at index 0. In Python lists, pop(index) removes and returns the item at the given index, so S.pop(0) removes 10. S.pop() would remove the last list element, 6, which is not the top in this specified implementation.