Program for Stack Implementation using List in Python

Program for Stack Implementation in Python

Stack is a linear data structure. Stack is a list of elements in which an element may be inserted or deleted only at one end, called the TOP of the stack. It works on the principle of LIFO. LIFO stands for Last In First Out. Two basic operations of Stack are PUSH and POP.

PUSH - Inserting element at top of the stack.
POP - Deleting element at top of the stack.



This is the basic understanding of Stack. Now, let's see the program for implementation of stack using list in python.

Source Code

def isempty(stk):          # checks whether the stack is empty or not
   if stk==[]:
      return True
   else:
      return False
#-------------------------------------------------------------
def push(stk,item):        # Allow additions to the stack
   stk.append(item)
   top=len(stk)-1
#-------------------------------------------------------------
def popu(stk):
   if isempty(stk):        # verifies whether the stack is empty or not
      print("Stack Underflow")
   else:    # Allow deletions from the stack
      item=stk.pop()
      if len(stk)==0:
         top=-1
      else:
         top=len(stk)
      return item
#--------------------------------------------------------
def display(stk):
   if isempty(stk):
      print("Stack is empty")
   else:
      top=len(stk)-1
      print("Elements in the stack are: ")
      for i in range(top,-1,-1):
         print (stk[i])

#------------------Driver code-------------------------
stk=[]     # Emptry list as empty stack
top=-1
while True:
    print("Enter your choice:\n1.PUSH\n2.POP\n3.Display\n4.Exit")
    ch=int(input())  # <-user coice
    if ch==1:   #PUSH in stack
        k=input("Enter element to insert: ")
        push(stk,k)
    elif ch==2:  #POP in stack
        k=popu(stk)
        print(k," is popped")
    elif ch==3:   # Display Stack
        display(stk)
    elif ch==4:   #Exiting from loop
        break
    else:   
        print("Invalid Choice...")
       
You can copy this code and run in your IDE. This is a menu based stack implementation using list in python.

I hope you liked our content. If you have any doubt related to this you can ask in the comments below. Also, your appreciation is welcomed in the comments.


Enjoy Coding!!!

For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment

For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.

Post a Comment (0)

Previous Post Next Post