We can implement a stack using a list in Python , as a list is a dynamic data structure that can grow or shrink as needed.
We can use the built-in methods of list, such as append and pop , to perform push and pop operations on the stack.
We can also use the len function to get the size of the stack, and check if it is empty or full.
Here is an example of how to implement a stack using a list in Python:
-
create an empty list to store the stack elements
stack = []
-
define a function to push an element to the stack
def push(element):
# append the element to the end of the list
stack.append(element)
# print a message to indicate successful operation
print(element, “pushed to stack”)
-
define a function to pop an element from the stack
def pop():
# check if the stack is empty
if len(stack) == 0:
# print a message to indicate error
print(“Stack is empty”)
# return None
return None
else:
# pop and return the last element of the list
element = stack.pop()
# print a message to indicate successful operation
print(element, “popped from stack”)
# return the element
return element
-
test the functions
push(10) # 10 pushed to stack
push(20) # 20 pushed to stack
push(30) # 30 pushed to stack
pop() # 30 popped from stack
pop() # 20 popped from stack
pop() # 10 popped from stack
pop() # Stack is empty