Table of Contents

Python Stack Display Function

Example Description
Learn how to effectively display stack elements in Python. Explore the display function designed to showcase the current elements within a stack. Dive into practical examples and enhance your understanding of stack data structures through visualization.

Introduction:

Visualizing the contents of a stack is essential for understanding how stack data structures work. In this tutorial, we introduce the display function, which enables the visualization of stack elements. By providing a hands-on example, you’ll gain insight into printing stack elements in reverse order, improving your grasp of Python stack operations.

Code:

def display(glassStack):
  x=len(glassStack)
  print("Current elements in the stack are: ")
  for i in range(x-1,-1,-1):
     print(glassStack[i])
# First, create a glassStack list
glassStack = [1, 2, 3, 4]

# Call the display function to print the elements in the stack
display(glassStack)

Logic:

  1. Define the display function with a parameter named glassStack, representing the stack to be displayed.
  2. Calculate the length of the glassStack using the len() function and assign it to x.
  3. Print a message indicating “Current elements in the stack are:” to set the context for the output.
  4. Use a for loop to iterate through the elements of the glassStack in reverse order (from the last element to the first):
  5. Initialize i with the value x-1.
  6. Loop until i is greater than or equal to 0.
  7. Print the element at index i of the glassStack.
  8. Decrement i by 1 in each iteration.
  9. Create a list named glassStack with initial elements [1,2,3,4].
  10. Call the display function, passing the glassStack list as an argument, to print the elements in reverse order

Output:

>>Current elements in the stack are:

>>4

>>3

>>2

>>1