Computer Science · Ch 3 — Stack
Implementation of Stack in Python
Implementation of Stack in Python
A stack is an ordered, linear collection where all insertions and deletions happen at one end — the top. In Python, the simplest way to build a stack is to use the built-in list type. You can treat either end of the list as the top, but the natural choice is the rightmost end, because Python’s append() and pop() methods already work there efficiently. When you use these built-in methods, you do not need to explicitly track a TOP variable — the list itself keeps track of where the top is.
The textbook walks through a complete example: a stack of glasses (like the one shown in Figure 3.2 of the chapter). The program lets you insert/delete glasses, check if the stack is empty, find how many glasses are in it, read the topmost glass’s label, and display all glasses.
Creating an empty stack
You start with an empty list:
glassStack = list()
This creates a stack named glassStack that contains no elements.
Function: isEmpty — check if the stack is empty
Trying to remove an element from an empty stack causes underflow. This function returns True if the stack has no elements, and False otherwise.
def isEmpty(glassStack):
if len(glassStack) == 0:
return True
else:
return False
Function: opPush — insert (push) an element
Push always adds a new element at the top of the stack. Since we are using the right end of the list as the top, we call append().
def opPush(glassStack, element):
glassStack.append(element)
In Python, lists have no fixed size limit (other than available memory). So a stack implemented this way will never be full — you will never face an overflow condition.
Function: size — count the elements
Use Python’s len() function to return the number of elements currently in the stack.
def size(glassStack):
return len(glassStack)
Function: top — read the topmost element without removing it
First check if the stack is empty. If it is, print a message and return None. Otherwise, access the last element of the list (index len(glassStack) - 1) and return it.
def top(glassStack):
if isEmpty(glassStack):
print('Stack is empty')
return None
else:
x = len(glassStack)
element = glassStack[x - 1]
return element
Function: opPop — delete and return the topmost element
This function takes the stack name as its only parameter. It first checks for underflow — if the stack is empty, it prints 'underflow' and returns None. Otherwise, it calls pop() (which removes and returns the last element of the list) and returns that value.
def opPop(glassStack):
if isEmpty(glassStack):
print('underflow')
return None
else:
return glassStack.pop()
Function: display — show all elements in the stack
To display the stack from top to bottom, you need to iterate from the last index down to the first (index 0). The loop uses range(x-1, -1, -1).
def display(glassStack):
x = len(glassStack)
print("Current elements in the stack are: ")
for i in range(x - 1, -1, -1):
print(glassStack[i])
Putting it all together — the main program
After defining the functions, the textbook gives a complete driver program that:
- Creates an empty stack.
- Pushes
'glass1'and'glass2'. - Prints the current size (2).
- Pops one element (removes
'glass2'). - Pushes
'glass3'. - Reads and prints the top element (
'glass3'). - Displays all elements (top to bottom:
glass3, thenglass1). - Empties the stack by repeatedly popping until
Noneis returned.
glassStack = list() # create empty stack
# add elements to stack
element = 'glass1'
print("Pushing element ", element)
opPush(glassStack, element)
element = 'glass2'
print("Pushing element ", element)
opPush(glassStack, element)
# display number of elements in stack
print("Current number of elements in stack is", size(glassStack))
# delete an element from the stack
element = opPop(glassStack)
print("Popped element is", element)
# add new element to stack
element = 'glass3'
print("Pushing element ", element)
opPush(glassStack, element)
# display the last element added to the stack
print("top element is", top(glassStack))
# display all elements in the stack
display(glassStack)
# delete all elements from stack
while True:
item = opPop(glassStack)
if item == None:
print("Stack is empty now")
break
else:
print("Popped element is", item)
Output of the program
Pushing element glass1
Pushing element glass2
Current number of elements in stack is 2
Popped element is glass2
Pushing element glass3 …