Identify the correct code for the following:
A function named 'op' is used to delete the topmost element from the stack. It takes one parameter - the name of the stack (gStack) from which element is to be deleted and returns the value of the deleted element. The function first checks whether the stack is empty or not. If it is not empty, it removes the topmost element from it.
Identify the correct code for the following:
A function named 'op' is used to delete the topmost element from the stack. It takes one parameter - the name of the stack (gStack) from which element is to be deleted and returns the value of the deleted element. The function first checks whether the stack is empty or not. If it is not empty, it removes the topmost element from it.
Solution
Option 1 checks whether the stack is empty with isEmpty(gStack). If it is, it prints 'underflow' and returns None. Otherwise it removes the topmost element with gStack.pop() and returns that value. This is the standard pop operation for a stack implemented as a Python list.
Option 2: no underflow check, so pop() on an empty list raises an IndexError.
Option 3: handles only the empty case. When the stack is not empty, nothing is removed and nothing is returned.
Option 4: del is a Python keyword, not a list method, so gStack.del() is a syntax error. The list method that removes the last element is pop().
Related questions:
2026: 29 May Shift 2
2026: 21 May Shift 1
2025: 21 May Shift 1
2026: 11 May Shift 2