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 queueempty()
: Return true if the queue is empty else falsefull()
: Return true if the queue maximum size is reached. If the queuemaxsize=0
then the method will never return trueget()
: Return and remove an item from the queue. If the queue is empty, wait until an item is availableput(item)
: Puts an item into the queue. If the queue is full, wait until a free slot is availableqsize()
: 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. More articles
- Python Tutorial for Beginners
- Python Random Module Tutorial
- Python input() method Tutorial
- Python RegEx Tutorial
- Python JSON Example
- Introduction to the Flask Python Web App Framework
- Selenium with Python Example
5. Download the Project
This was a tutorial on the queue module in python programming.
You can download the full source code of this example here: Queue in Python
Last updated on May 18th, 2021