WWW Softwaretestinghelp Com Python Python Queue Tutorial
WWW Softwaretestinghelp Com Python Python Queue Tutorial
Home Resources FREE EBooks QA Testing Courses Automation Types Of Testing Tutorials Data
Python Queue Tutorial: How To Implement And Use Python About SoftwareTestingHelp
Queue
Helping our community since 2006!
Most
Last Updated: March 24, 2023
popular portal for Software professionals
with 300 million+ visits and 400,000+
This Python Queue tutorial will discuss pros, cons, uses, types, and operations on Queues along with followers! You will absolutely love our
its implementation with programming examples: creative content on QA, Dev, Software
Tools & Services Reviews!
In Python, a Queue is a linear data structure that follows the FIFO approach.
Here FIFO refers to “ First In First Out “ i.e. the first element entered in the queue will be popped out
first. Or we can say that this approach is the exact opposite of the Stack data structure.
Python Queue
Advantages
Disadvantages
Applications
Types of Queue
#1) Python Simple Queue
#2) Python Circular Queue
#3) Python Priority Queue
#4) Python Deque (Double-ended queue)
Operations on Queue
How to Implement Queue in Python
Methods of Queue
Frequently Asked Questions
Conclusion
Recommended Reading
Python Queue
Recommended Reading
Python Variables
Python String Split Tutorial
How to Test Application Messaging Queue:
IBM WebSphere MQ Intro Tutorial
Python Operators
Python String Functions – Tutorial With
Examples
Java Priority Queue Tutorial – Implementation
& Examples
Java Queue – Queue Methods, Queue
Implementation With Examples
Let us understand the queue with the real-world example of “ Cinema ticket counter ”. While buying the Queue Data Structure In C++ With Illustration
tickets for the movie, people stand in a queue at the ticket counter.
The second person or the third person will buy the ticket only if the first person or second person gets
the ticket from the counter. The second person cannot break the queue to buy the ticket first.
Here the first person will buy the ticket first and only then the turn will come for the second person.
The Python queue works on the above principle.
Disadvantages
It is not easy to delete the elements from the middle.
Difficult to create and maintain.
It is a non-linear data structure that takes a large amount of memory when compared to linear
data structures.
Applications
The queue data structure is used when we want to organize the group of objects in a particular order.
The second person or the thing cannot use the resources until the first person or thing releases that
resource.
It serves the request on a single shared resource. For example, Printer, CPU, etc.
If we relate it with the real-world example then, the call center is one of the powerful examples of
a queue.
If any issue occurs, it can be resolved in the FIFO order i.e. the issue which occurs first will be
resolved first.
Types of Queue
#1) Python Simple Queue
In the simple queue data structure, the insertion of the element takes place at the rear and removes
from the front position. It follows the FIFO criteria.
```
class demo_queue:
def __init__(self):
self.queue = list()
def add_demo_element(self,element):
def size(self):
return len(self.queue)
Queue = demo_queue()
Queue.add_demo_element("Monday")
Queue.add_demo_element("Tuesday")
Queue.add_demo_element("Wednesday")
print(Queue.size())
```
#2) Python Circular Queue
In the circular queue data structure, the last element of the queue is assigned as the first element of a
queue to make a circular link between the items i.e. we can add the new element at the first position.
```
class CircularQueueDemo():
def printdemoCQueue(self):
if(self.head == -1):
print("No element present in the demo circular queue")
obj = CircularQueueDemo(5)
obj.Enqueue(1)
obj.Enqueue(2)
obj.Enqueue(3)
obj.Enqueue(4)
obj.Enqueue(5)
print( " Demo Queue: " )
obj.printdemoCQueue()
obj.Dequeue()
print( " Demo Queue after removing the elements " )
obj.printdemoCQueue()
```
#3) Python Priority Queue
A priority queue data structure is unique from all the other types of the queue because, in this queue,
each element has its own priority according to which all the elements are served. Suppose if the two
elements have the same priority then, they will be served on the basis of their order.
```
class PriorityQueueDemo(object):
def __init__(self):
self.queue = []
def __str__(self):
return ' '.join([str(i) for i in self.queue])
def Is_Queue_Empty(self):
return len(self.queue) == 0
# Removing the elements from the demo queue on the basis of their priority
def Remove_elements(self):
try:
max = 0
for i in range(len(self.queue)):
if self.queue[i] > self.queue[max]:
max = i
items = self.queue[max]
del self.queue[max]
return items
except IndexError:
print()
exit()
if __name__ == '__main__':
demoQueue = PriorityQueueDemo()
demoQueue.Add_elements(11)
demoQueue.Add_elements(2)
demoQueue.Add_elements(45)
demoQueue.Add_elements(72)
print(demoQueue)
while not demoQueue.Is_Queue_Empty():
print(demoQueue.Remove_elements())
```
It does not follow the FIFO approach. In this queue, the addition and removal of the element take place
from both sides i.e. rear and front.
How to use Deque (Double-ended queue) in Python?
```
import collections
DemoDoubleEnded = collections.deque(["Monday","Tuesday","Wednesday&
print (DemoDoubleEnded)
```
Operations on Queue
The basic queue operations are:
Program
```
class Demo_Queue:
def __init__(self):
self.items = []
def Is_Empty(self): # This function will check whether the queue is empty or not
return self.items == []
def Enqueue(self, data):
self.items.append(data) # here we are appending the elements in the queue
def Dequeue(self):
return self.items.pop(0) # here we are performing the Dequeue operation
demo_queue = Demo_Queue()
while True:
print('Enqueue operation ')
print('Dequeue operation’')
print('Quit')
task = input('What would you like to do? ').split()
operations = task[0].strip().lower()
if operations == 'Enqueue': # Condition
demo_queue.Enqueue(int(task[1])) # Append the element in the queue
elif operations == 'Enqueue':
if demo_queue.Is_empty():
print('Demo Queue is empty.')
else:
print('Dequeued value: ', demo_queue.Dequeue())
elif operations == 'Quit':
break
```
Output
Enqueue:
Program
```
class Demo_Queue:
def __init__(self):
self.queue = list()
# Inserting the elements
def insert_element(self,val):
if val not in self.queue:
self.queue.insert(0,val)
return True
return False
def size(self):
return len(self.queue)
demo_queue = Demo_Queue()
demo_queue.insert_element("A")
demo_queue.insert_element("B")
demo_queue.insert_element("C")
demo_queue.insert_element("D")
In the above program, we are creating a queue and inserting the elements into it.
Output:
Dequeue:
Program
```
demo_queue = []
demo_queue.append('S') # Adding the elements to the list
demo_queue.append('T')
demo_queue.append('H')
In the above program, we create a demo queue and add the elements. After the insertion of elements,
we delete all the elements from the queue.
Output:
Methods of Queue
Python supports the various methods of Queue, that are most commonly used while working with the
queue data structure.
Answer: In Python, to insert the element in the queue, the “ put() ” function is used. It is known as an
enqueue operation.
To delete the element in the queue the “ get() ” function is used. It is known as the dequeue
operation.
The Python queue works on the FIFO ( First In First Out ) principle i.e. the element which is stored
first will be deleted first.
Answer: To use the queue in Python “ from queue import Queue “ is used.
```
from queue import Queue
demo = Queue()
demo.size() # it will give the size of the queue
demo.empty() # it will tell whether the queue is empty or not
demo.put(item)
demo.get()
```
Answer: To check if the queue is empty or not follow the below algorithm:
Add the front element and store it in a variable then, initialize it with zero.
Pop the front element of the queue.
Repeat the above steps to empty the queue.
Then, print the output value of the variable.
Example
```
import queue # Here we are importing the queue class
print(demo.get()) # Elements are deleted from the queue using the “get()” function from the queue
print(demo.get())
print(demo.get())
print(demo.get())
```
Example:
```
demo_queue = []
demo_queue.append(‘Software’)
demo_queue.append(‘Testing’)
demo_queue.append(‘Help’)
```
Conclusion
In this tutorial, we discussed the Queue data structure. The queue is a non-linear data structure that
uses the FIFO principle.
Recommended Reading
Python Variables
Python String Split Tutorial
How to Test Application Messaging Queue: IBM WebSphere MQ Intro Tutorial
Python Operators
Python String Functions - Tutorial With Examples
Java Priority Queue Tutorial - Implementation & Examples
Java Queue - Queue Methods, Queue Implementation With Examples
Queue Data Structure In C++ With Illustration
© COPYRIGHT SOFTWARETESTINGHELP 2023 — READ OUR COPYRIGHT POLICY | PRIVACY POLICY | TERMS | COOKIE POLICY | AFFILIATE DISCLAIMER