python list as stack and queue

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 Pop(stk):
   if isEmpty(stk): # verifies whether the stack is empty or not
      print("Underflow")
   else: # Allow deletions from the stack
      item=stk.pop()
      if len(stk)==0:
         top=None
      else:
         top=len(stk)
         print("Popped item is "+str(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 (str(stk[i]))

# executable code
if __name__ == "__main__":
   stk=[]
   top=None
   Push(stk,1)
   Push(stk,2)
   Push(stk,3)
   Push(stk,4)
   Pop(stk)
   Display(stk)

3.78
9
Awgiedawgie 440215 points

                                    #Adding elements to queue at the rear end
def enqueue(data):
   queue.insert(0,data)

#Removing the front element from the queue
def dequeue():
   if len(queue)>0:
      return queue.pop()
   return ("Queue Empty!")

#To display the elements of the queue
def display():
   print("Elements on queue are:");
   for i in range(len(queue)):
      print(queue[i])

# executable code
if __name__=="__main__":
   queue=[]
   enqueue(5)
   enqueue(6)
   enqueue(9)
   enqueue(5)
   enqueue(3)
   print("Popped Element is: "+str(dequeue()))
   display()

3.78 (9 Votes)
0
Are there any code examples left?
Create a Free Account
Unlock the power of data and AI by diving into Python, ChatGPT, SQL, Power BI, and beyond.
Sign up
Develop soft skills on BrainApps
Complete the IQ Test
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source