How to iterate through a Python Queue.Queue with a for loop instead of a while loop?

You can use iter with callable. (You should pass two arguments, one for the callable, the other for the sentinel value)

for job in iter(queue.get, None): # Replace `None` as you need.
    # do stuff with job

NOTE This will block when no elements remain and no sentinel value is put. Also, like a whileget loop and unlike normal for loops over containers, it will remove items from the queue.

None is common value, so here’s a sample with more concrete sentinel value:

sentinel = object()
for job in iter(queue.get, sentinel):
    # do stuff with job

Leave a Comment