Skip to main contentSkip to solution

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

✅ Correct Option: 1

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().

Keyboard Shortcuts

  • Left arrow: Previous question
  • Right arrow: Next question
  • S key: Jump to solution
  • Q key: Jump to question