Creating Queues With .append()
In the last lesson, you learned how the
.append() method can be used with other list methods to implement a stack. In this lesson, you’ll learn how to use them to implement a queue.
00:11 But first, what is a queue? A queue is a data structure that can be viewed as a pipe. You put things in at one end of the queue and things come out at the other end.
00:22 Or maybe like standing in line. You get into the line at the end and eventually work your way up to the front. It is a First-In/First-Out structure. The first thing that gets in line, or into the queue, will be the first thing removed at the other end.
00:39 There are two main operations. Enqueue adds something to the end of the queue and dequeue removes the item at the front of the queue. It also returns that item to be used by the calling agent which asked for it.
Implementing this with a list, again,
.append() will be used to enqueue—add or append something to the end of the list. Dequeue will be implemented with
.pop(), providing an argument of
This always pops off the element at the front of the list, which is being viewed as the front of this queue. So, here’s the implementation. This file is called
list_queue.py because it’s a queue data structure implemented using a list. It begins with
The initializer is essentially the same. A list is created and saved to the attribute
._items. Here are the two main operations:
.append() to add something to the end of the queue. And
.pop() with an argument of
0 to pop things off from the front of the queue, and that item is returned.
Here again is that
except block used to react to an attempt to dequeue from an empty queue. Dunder methods
.__repr__() have been implemented here similar to how they were for the stack. And you can see this work as well.
We create a queue. The initializer takes no arguments. Let’s enqueue the numbers
2 and then inspect the queue, again just asking for its representation or asking it to be printed. It uses the
.__repr__() dunder method.
len() function will find its length, since we defined that. And now remove some things from the queue.
First was the
1. Notice how the first thing we put into the queue was the first thing taken out. This is one of the things that makes a queue different from a stack. First in, first out. So the
1 comes out first
and then the
2. There are other existing Python data structures that also have implemented an
.append() method, and you’ll see a couple of those in the next few lessons.
Become a Member to join the conversation.