Home » Python » Queue in Python

About Yatin

Working as a Technical Lead in the Information Technology sector where I'm primarily involved with projects based on Java/J2EE Technologies platform (such as Spring, Spring Boot, Hibernate, Redis, etc.), novel UI technologies (Angular & React), Docker, and AWS. Recently completed the AWS Solution Architect Associate Certification.

Queue in Python

Hello in this tutorial, we will understand how to implement queues in python programming.

1. Introduction

Queues in Python are the data containers. There are three types of queues in python programming –

  • First-in-First-out Queue: This queue process the data in the way it is entered
  • Last-in-First-out Queue: This queue is similar to the FIFO queue except that it is in the last-in-first-out order
  • Priority Queue: This queue returns the item in the order of the priority. So when an item is added its priority is also set. During retrieval, they are returned in the priority order and the lower number of priority items are returned first

There are various methods available in this module.

  • maxsize: Number of items allowed in the queue. Max size of zero means an infinite queue
  • empty(): Return true if the queue is empty else false
  • full(): Return true if the queue maximum size is reached. If the queue maxsize=0 then the method will never return true
  • get(): Return and remove an item from the queue. If the queue is empty, wait until an item is available
  • put(item): Puts an item into the queue. If the queue is full, wait until a free slot is available
  • qsize(): Return the count of items in the queue

1.2 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

2. Queues in Python

I am using JetBrains PyCharm as my preferred IDE. You are free to choose the IDE of your choice. Let us dive in with the programming stuff now.

2.1 FIFO Queue

Let us understand the FIFO queue in python programming.

FIFO Queue

# python queue tutorial

# implementing FIFO (First-in-First-out queue)


# importing the queue module
from queue import Queue


def add(q):
    for i in range(1, 6):
        # adding elements to the queue
        q.put(i)

    # printing elements present in the queue
    print_ele(q)


def print_ele(q):
    # checking if the queue is empty
    if not q.empty():
        queue_size = q.qsize()
        print('Queue size = {}. Printing elements.'.format(queue_size))
        for i in range(queue_size):
            print('{}'.format(q.get()))  # printing the item that we are removing
    else:
        # if the queue is empty print the queue size
        print('Queue empty! Size = {}'.format(q.qsize()))


# driver code
if __name__ == '__main__':
    # optional parameter to specify the max size of the queue
    # maxsize = 10
    # taking an object of Queue
    q = Queue()
    add(q)

If everything goes well the following output will be shown in the IDE console.

Console output

Queue size = 5. Printing elements.
1
2
3
4
5

2.2 LIFO Queue

Let us understand the LIFO queue in python programming.

LIFO Queue

# python queue tutorial

# implementing LIFO (Last-in-First-out queue)


# importing the LIFO queue module
from queue import LifoQueue


def add(q):
    for i in range(1, 6):
        # adding elements to the queue
        q.put(i)

    # printing elements present in LIFO queue
    print_ele(q)


def print_ele(q):
    # checking if the queue is empty
    if not q.empty():
        queue_size = q.qsize()
        print('Queue size = {}. Printing elements.'.format(queue_size))
        for i in range(queue_size):
            print('{}'.format(q.get()))  # printing the item that we are removing
    else:
        # if the queue is empty print the queue size
        print('Queue empty! Size = {}'.format(q.qsize()))


# driver code
if __name__ == '__main__':
    # optional parameter to specify the max size of the queue
    # maxsize = 10
    # taking an object of LIFO Queue
    q = LifoQueue()
    add(q)

If everything goes well the following output will be shown in the IDE console.

Console output

Queue size = 5. Printing elements.
5
4
3
2
1

2.3 Priority Queue

Let us understand the Priority queue in python programming.

Priority Queue

# python queue tutorial

# implementing priority queue


import random
# importing the priority queue module
from queue import PriorityQueue


def add(q):
    for i in range(1, 6):
        # adding random elements to the priority queue
        q.put(random.randint(1, 100))

    # printing elements present in priority queue
    print_ele(q)


def print_ele(q):
    # checking if the queue is empty
    if not q.empty():
        queue_size = q.qsize()
        print('Queue size = {}. Printing elements.'.format(queue_size))
        for i in range(queue_size):
            print('{}'.format(q.get()))  # printing the item that we are removing
    else:
        # if the queue is empty print the queue size
        print('Queue empty! Size = {}'.format(q.qsize()))


# driver code
if __name__ == '__main__':
    # optional parameter to specify the max size of the queue
    # maxsize = 10
    # taking an object of Priority Queue
    q = PriorityQueue()
    add(q)

If everything goes well the following output will be shown in the IDE console.

Console output

Queue size = 5. Printing elements.
18
19
50
62
64

2.4 Queue using List

Let us understand the queue using a list in python programming.

Queue using List

# python enqueue and dqueue
# using list

class DQueue:
    # initialize the queue
    def __init__(self):
        self.queue = []

    # add an element to the queue
    def enqueue(self, item):
        max_size = 5
        if self.size() > max_size:
            print("Queue is full.")
        else:
            self.queue.append(item)

    # remove an element from the queue
    def dequeue(self):
        if self.size() < 1:
            return None
        return self.queue.pop(0)

    # display the queue elements
    def display(self):
        print(self.queue)

    # return the queue length
    def size(self):
        return len(self.queue)


# driver code
if __name__ == '__main__':
    q = DQueue()

    # adding elements to the queue
    for i in range(1, 6):
        q.enqueue(i)

    # display the queue elements
    print('Elements in queue.')
    q.display()

    # remove an element from the queue
    print('\nPopping out the element from the queue.')
    q.dequeue()  # removes '1'

    # display the queue elements
    print('\nAfter removing an element.')
    q.display()

If everything goes well the following output will be shown in the IDE console.

Console output

Elements in queue.
[1, 2, 3, 4, 5]

Popping out the element from the queue.

After removing an element.
[2, 3, 4, 5]

2.5 Dequeue using Collections

Let us understand the dequeue using collections in python programming.

Dequeue using Collections

# dequeue from collections

from collections import deque

# initialize the queue
q = deque()

# adding elements to the queue
for i in range(1, 6):
    q.append(i)

print('Initial queue is: {}\n'.format(q))

# remove an element from the queue
print('Removing element = {}'.format(q.popleft()))  # removes '1'
print('Removing element = {}'.format(q.popleft()))  # removes '2'

print('\nAfter Removing elements: {}'.format(q))

If everything goes well the following output will be shown in the IDE console.

Console output

Initial queue is: deque([1, 2, 3, 4, 5])

Removing element = 1
Removing element = 2

After Removing elements: deque([3, 4, 5])

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned:

  • The Queue module in python programming
  • Sample program to understand and implement the different queues

You can download the source code of this tutorial from the Downloads section.

4. Download the Project

This was a tutorial on the queue module in python programming.

Download
You can download the full source code of this example here: Queue in Python

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments