Table of Contents

Python Stack Top Function

Example Description
Discover the Python top function's role in obtaining the top element of a stack. Explore implementation details and practical examples showcasing stack element retrieval. Enhance your understanding of stack data structures through clear explanations and hands-on demonstrations.

Introduction:

The top function in Python plays a crucial role in accessing the top element of a stack without removing it. In this tutorial, we delve into the implementation and usage of the top function, which ensures efficient stack element retrieval. Through practical examples and explanations, you’ll gain insights into managing and navigating stack data structures using Python.

Code:

def isEmpty(glassStack):
    return len(glassStack) == 0

def top(glassStack):
    if isEmpty(glassStack):
        print('Stack is empty')
        return None
    else:
        x = len(glassStack)
        element = glassStack[x - 1]
        return element

# Test the top function
glassStack = [1, 2, 3, 4]
result = top(glassStack)
print(result)  # Output: 4

empty_stack = []
result_empty = top(empty_stack)
print(result_empty)  # Output: Stack is empty

Logic:

  1. Define the isEmpty function to check if a stack is empty.
  2. Define the top function with a parameter named glassStack to retrieve the top element of the stack.
  3. Check if the stack is empty using the isEmpty function.
  4. If the stack is empty, print ‘Stack is empty’ and return None.
  5. If the stack is not empty, calculate the length of the glassStack and assign it to x.
  6. Access the top element of the stack by retrieving glassStack[x-1] and return it
  7. Initialize a glassStack list with elements [1,2,3,4].
  8. Call the top function with the glassStack list as an argument and print the returned value. The expected output is 4.
  9. Initialize an empty empty_stack list.
  10. Call the top function with the empty_stack  list as an argument and print the returned value. The expected output is ‘Stack is empty’.

Output:

>>4

>>Stack is empty