How to Iterate through a Queue in Python

If you are looking for ways to “iterate through a Queue in Python”, keep reading. This article will give you a few methods to loop over a queue with detailed examples and explanations. 

Queue in Python

The Queue is a data structure that stores and retrieves items in a first-in, first-out (FIFO) manner. In other words, the first item you add to the Queue will be the first one to be removed.

In Python, you can use the queue.Queue class from the queue module to create a queue. Here is an example of how you can create a queue and add items to it:

Code:

from queue import Queue
 
# Create a queue
q = Queue()
 
# Add some items to the Queue
q.put("item1")
q.put("item2")
q.put("item3")

How to Iterate through a Queue in Python

In the first part, we showed you how to create a Queue. Now, we will provide a few methods to iterate through the Queue.

Use a for loop

As with other data structures, you can loop over a Queue by using a “for” loop. The range of the Queue can be taken by the qsize() method, and the items can be taken by the get() method. Keep in mind that the get() method removes the item from the Queue, so by the end of the loop, the Queue will be empty

Code:

from queue import Queue
 
# Create a queue
q = Queue()
 
# Enqueue some items
q.put("item1")
q.put("item2")
q.put("item3")
 
# Iterate through the queue
for i in range(q.qsize()):
    item = q.get()
    print(item)

Result:

item1
item2
item3

Check if the Queue is not empty

Also, you can use the while loop to check if the Queue is not empty, then take each element.

Code

from queue import Queue
 
# Create a queue
q = Queue()
 
# Enqueue some items
q.put("item1")
q.put("item2")
q.put("item3")
 
# Iterate through the Queue
while not q.empty():
    item = q.get()
    print(item)

Result:

item1
item2
item3

Use the Queue.Queue object’s queue attribute

If you want to iterate through the Queue without removing the items, you can use the object’s queue attribute, a list-like object containing the items in the Queue.

Code:

from queue import Queue
 
# Create a queue
q = Queue()
 
# Enqueue some items
q.put("item1")
q.put("item2")
q.put("item3")
 
# Iterate through the Queue
for item in q.queue:
    print(item)

Result:

item1
item2
item3

Summary

In summary, you can iterate through a Queue in Python in two ways: Use the for loop or check if the Queue is not empty, then use the get() function to pick out each element or use the queue attribute to loop the Queue without picking out the elements.

Leave a Reply

Your email address will not be published. Required fields are marked *