Introduction:
Manipulating stack elements is a crucial skill in programming. In this tutorial, we delve into the opPop function, which facilitates the removal of the top element from a stack. Through practical examples, you’ll learn how to utilize this function to pop elements and handle underflow situations, enhancing your understanding of stack data structures in Python.
Code:
def isEmpty(glassStack):
return len(glassStack) == 0
def opPop(glassStack):
if isEmpty(glassStack):
print('underflow')
return None
else:
return glassStack.pop()
# Test the opPop function
glassStack = [1, 2, 3, 4]
result = opPop(glassStack)
print(result) # Output: 4
print(glassStack) # Output: [1, 2, 3] (the last element 4 is removed)
empty_stack = []
result_empty = opPop(empty_stack)
print(result_empty) # Output: underflow
Logic:
- Define the isEmpty function with a parameter named glassStack, which returns True if the stack is empty (length is 0) and False otherwise.
- Define the opPop function with a parameter named glassStack
- Check if the stack is empty using the isEmpty function.
- If the stack is empty, print ‘underflow’, indicating that there is no element to pop, and return None.
- If the stack is not empty, use the pop() method to remove and return the top element of the stack.
- Initialize a glassStack list with elements [1,2,3,4].
- Call opPop(glassStack) and print the returned value. The expected output is 4.
- Print the updated glassStack list after the pop operation, which should now be [1,2,3].
- Initialize an empty empty_stack list.
- Call opPop(glassStack) and print the returned value. The expected output is ‘underflow’.
Output:
>>4
>>[1, 2, 3]
>>underflow