Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Creating Queues With .append()

00:00 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.

00:54 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 0.

01:07 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 because it’s a queue data structure implemented using a list. It begins with class Queue:.

01:29 The initializer is essentially the same. A list is created and saved to the attribute ._items. Here are the two main operations: .enqueue() and .dequeue().

01:42 .enqueue() uses .append() to add something to the end of the queue. And .dequeue() uses .pop() with an argument of 0 to pop things off from the front of the queue, and that item is returned.

01:58 Here again is that try/except block used to react to an attempt to dequeue from an empty queue. Dunder methods .__len__() and .__repr__() have been implemented here similar to how they were for the stack. And you can see this work as well.

02:23 We create a queue. The initializer takes no arguments. Let’s enqueue the numbers 1

02:38 and 2 and then inspect the queue, again just asking for its representation or asking it to be printed. It uses the .__repr__() dunder method.

02:58 And the len() function will find its length, since we defined that. And now remove some things from the queue.

03:10 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

03:29 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.