How to Iterate through a Queue in Python

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

Iterate through a Queue in Python #

Use a while loop to iterate through a queue in Python, e.g. while not q.empty():. The loop checks if the queue is not empty and iterates as long as there are items in the queue.

main.py
import queue q = queue.Queue() for item in range(10): q.put(item) while not q.empty(): item = q.get() print(item) # 👉️ 0 1 2 3 4 ...

The queue.empty method returns True if the queue is empty, and False otherwise.

We use this approach to prevent blocking after the queue has been emptied.

Note that the queue.get method removes and returns an item from the queue.

Alternatively, you can use the queue attribute on the queue to get access to a deque object and iterate over the object using a for loop.

main.py
import queue q = queue.Queue() for item in range(10): q.put(item) for item in q.queue: print(item) # 👉️ 0 1 2 3 4 ...

Deque objects support indexing and iteration, so we can iterate over a queue as if we were iterating over a list.

The example above doesn't use the queue.get() method, so it doesn't remove items from the queue.

Alternatively, you can use the iter() function.

main.py
import queue q = queue.Queue() for item in range(10): q.put(item) sentinel = object() for item in iter(q.get, sentinel): print(item) # 👉️ 0 1 2 3 4 ... # 👇️ prevent queue from blocking after tasks finished q.put(sentinel) # 👈️ do this last

The iter function returns an iterator object.

After all of the work is finished, we add a sentinel value to the queue to raise StopIteration and prevent from blocking.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.