Table of Contents

Python Stack Operation

Example Description
Explore the opPop function in Python, designed to remove and return the top element from a stack. Discover the power of stack operations using practical examples. Learn how to handle underflow scenarios and streamline your programming skills.

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:

  1. Define the isEmpty function with a parameter named glassStack, which returns True if the stack is empty (length is 0) and False otherwise.
  2. Define the opPop function with a parameter named glassStack
  3. Check if the stack is empty using the isEmpty function.
  4. If the stack is empty, print ‘underflow’, indicating that there is no element to pop, and return None.
  5. If the stack is not empty, use the pop() method to remove and return the top element of the stack.
  6. Initialize a glassStack list with elements [1,2,3,4].
  7. Call opPop(glassStack) and print the returned value. The expected output is 4.
  8. Print the updated glassStack list after the pop operation, which should now be [1,2,3].
  9. Initialize an empty empty_stack list.
  10. Call opPop(glassStack) and print the returned value. The expected output is ‘underflow’.

Output:

>>4

>>[1, 2, 3]

>>underflow