How to implement a Queue in Python

Next Story

How to create framerate independent movement in Unity

A queue is a data structure commonly found in software engineering.

Let’s take some time to try to implement our own queue class in Python.

Queues work via First In First Out(FIFO) principals.

What that means is that the sooner an item is added to a list, the sooner that the item will be available to be removed from the list.

This is comparable to waiting in line for pizza. The people who got in line first will be the ones who get their pizza first.

class Queue():
    def __init__(self):
        self.array = []
    
    def add(self, item):
        self.array.append(item)
    
    def remove(self):
        if not len(self.array):
            return None
        item = self.array[0]
        del self.array[0]
        return item
    

In this code sample, we created a Queue class with 2 functions, add and remove.

The add function will take an item and add it to the queue.

The remove function will remove and return the first item in the queue.

https://www.googletagmanager.com/gtag/js?id=UA-63695651-4