From the course: Python Data Structures: Stacks, Deques, and Queues

List-based queues

- [Instructor] In this tutorial, we'll be looking at list-based queues in Python. A queue is a commonly used data structure. This follows the first in first out principle as we know. In this tutorial, we'll be implementing a list-based queue where the elements are stored in a list. So let's start off by defining a class for our queue. We'll go ahead and just call this queue. Now our class is going to have an init method that initializes the empty list queue and helps us draw our elements in it. Next let's define a method to help us add elements to our queue. This is known as enqueue. Now the enqueue method simply just uses the upend keyword and adds the item to the end of the list. Now the dequeue method first checks if the queue is empty. If it is, then it returns none because there are no values. If not, it removes the first item from the front of the list queue and then it returns it. We can also add in a method to check if the queue is empty. The is_empty method returns true if the length of the queue list is zero and false otherwise. This is done using the len keyword. And finally, let's add in a method to retrieve the size of our queue. The size method simply returns the length of the queue list. This again, is by using the len keyword. So now let's go ahead and expand on the list based queue implementation and include some sample values to help us illustrate how the queue works. So let's go to the bottom, and we'll go ahead and say queue is equal to queue to create an instance of the queue class. Now we're going to add some values to it. So we'll go ahead and say queue.enqueue, and we'll add in the value 10. If you remember, the enqueue function adds values to our queue. And then we'll go ahead and say queue.enqueue 20, queue.enqueue 30, and then queue.enqueue 40. Now if you go ahead and print out the size of our queue, it should print out as four. So we can go ahead and say queue.size. And if you go ahead and run this, we get the output of four. Now let's go ahead and check out our dequeue method. So we'll go ahead and create a new variable, and we'll call it value, and we'll say queue.dequeue. Now whatever item is the first in the queue will be removed, and it will be stored in this variable. So if we now go ahead and print out this value, we should get the value of 10, as we do. And that's it. We've now successfully implemented a list-based queue in Python. You can use these methods to enqueue and dequeue items, check if the queue is empty and even retrieve its size.

Contents