What is a Queue?

Formal Definition

In technical terms, a queue is a linear data structure that saves data in FIFO (First In / First Out) order. Conventionally, a queue’s members are private and only accessibly through its two primary operations (add/enqueue and pop/dequeue). It is the exact opposite of a stack.

What does this mean?

In everyday terms, a queue is like a list but with only two operations — adding an item to the back of the list and taking an item from the front of the list. When you “add” or “enqueue” an item to the queue, it puts that item at the back of the list. When you “pop” or “dequeue” an item from the queue, it removes the first item from the list.

A great way to remember how a queue works is just like a line. The person that got in line (or “enqueued”) first gets served (or “dequeued”) first.

Let’s 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.

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.

Previous Section

2.4 Stacks Next Section

2.6 Graphs**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.*