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