To implement the basic stack operations push and pop in python3.
It used to insert a data in the stack.
It using append() to add the data into the stack.
It used to remove an element from the list.
Pop function removes the top element first.
Because stack follows first in last out principle.
class Stack:
def __init__(self):
self.stack = []
#add the element in a stack
def add(self, data):
if data not in self.stack:
self.stack.append(data)
return True
else:
return False
#Use show to look all elements in the stack
def show(self):
return self.stack
#remove an element from stack
def remove(self):
if len(self.stack) <= 0:
return (“No element in the Stack”)
else:
return self.stack.pop()
#object creation
s = Stack()
#pass data in to the stack
s.add(“sathish”)
s.add(“Bala”)
s.add(“krishna”)
s.add(“Prakash”)
print(“*****Original Stack is****”)
print(s.show())
print(“\n”)
#removing data from the stack
print(“*****Removing following elements from stack****”)
print(s.remove())
print(s.remove())
print(“\n”)
print(“*****After removing****”)
print(s.show())