Data Structures in Python: Queue

The above figure shows a queue of people waiting to get the item. So, who do you think will get the item first? Of course, the one who came first. That means the person who came first will leave first.

Now, what if I told you this represents a data structure and this data structure is called a queue. Queue follows the pattern of FIFO(First In First Out) .i.e. the first element added in the queue is the first element removed.

You may think like the previous tutorial we can use a list in this also because we have an append method to add elements and using index we can remove the first element. But no, that's not an efficient method to do it because whenever any item is removed from the list every item after that needs to shift back to fill the gap created by removing that item. In this case, if we remove the first item then every other item will be shifted once backward which will make it too slow when executed. That's why we don’t use the list as a queue.

In Python collections module provides ‘deque’ which is fast and efficient for faster append and pops from both ends. Its execution is too simple:

Now we have to remove the element and for that, we would use ‘popleft’ method:

This will be enough for queue using deque in Python. We can create our own Queue class and create append and pop methods which I will show you tomorrow. See you and have a good day!


Lecture 1:

Lecture 2:

Lecture 3:

Lecture 4:

Lecture 5:

Lecture 6:

Lecture 7:

Lecture 8:

Lecture 9:

Lecture 10:

Lecture 11:

Lecture 12:

Lecture 13:

Lecture 14:

Lecture 15:

Lecture 16:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store