5️⃣

2.5 Queue

What is a Queue?

A queue is a linear data structure that saves data in First In / First Out order. This is the exact opposite of a stack.

Lets Look at the Code Below

Here we define a function called and make a list inside called queue_list. Inside that list we add some values in this case 100, 200 and 300. After we print the value we start removing values from the beginning of the list which in this case we would remove 100 first, then 200, and lastly 300 until we return an empty list.
A great way to remember how a queue works is just like a line or queue. The person that came first or gets served first leaves first.
 
Example 1:
def Queue(): # Make Stack List queue_list = [] # Appending Data To Stack List queue_list.append(100) queue_list.append(200) queue_list.append(300) print(queue_list) #Removes First Item "First In First Out" queue_list.pop(0) queue_list.pop(0) queue_list.pop(0) # Returns list return queue_list a = Queue() print(a)

Python Cleaner Implementation:

Below is the same as the code above but it uses classes.
class Queue: def __init__(self): # Make List self.queue_list = [] def appending(self, item): # Checks to see if there are any duplicates in list if item in self.queue_list: #If so it returns error return "Value Already Exists" else: self.queue_list.append(item) def pops(self): # Checks to see if list is empty if len(self.queue_list) != 0: # if it isn’t empty it removes first value return self.queue_list.pop(0) else: return "List is Empty" Check_Queue = Queue() #Should add value to list Check_Stack.appending(100) Check_Queue.appending(200) Check_Queue.appending(300) #Should print 300 and then 200 print(Check_Queue.pops()) print(Check_Queue.pops())
View code on GitHub.
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.