Getting Queue elements and iterating over a Queue in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
7 min

banner

# Table of Contents

  1. Get an item from a Queue in Python without removing it
  2. Get the First element of a Queue in Python
  3. Check if an element is in a Queue in Python
  4. Put multiple items in a Queue in Python
  5. Iterate through a Queue in Python
  6. Handle the queue.Empty exception in Python

# Get an item from a Queue in Python without removing it

Use the queue attribute on the queue to get an item from a queue without removing it, e.g. q.queue[0].

The queue attribute points to a deque object which supports indexing.

main.py
import queue q = queue.Queue() for item in range(10): q.put(item) print(q.queue[0]) # ๐Ÿ‘‰๏ธ 0 print(q.queue[0]) # ๐Ÿ‘‰๏ธ 0 print(q.queue[1]) # ๐Ÿ‘‰๏ธ 1

get item from queue without removing it

The code for this article is available on GitHub
The queue attribute gives us access to a deque object and deque objects support popleft() operations and indexing.

If you don't want to remove the specific element of the queue and only want to access it, use q.queue[0].

This approach also works if you use the PriorityQueue class.

main.py
import queue q = queue.PriorityQueue(maxsize=20) for item in range(10): q.put(item) print(q.queue[0]) # ๐Ÿ‘‰๏ธ 0 print(q.queue[0]) # ๐Ÿ‘‰๏ธ 0

You can also access the queue at a specific index if you use the collections.deque class.

main.py
from collections import deque deq = deque(['a', 'b', 'c']) print(deq[0]) # ๐Ÿ‘‰๏ธ 'a' print(deq[1]) # ๐Ÿ‘‰๏ธ 'b' print(deq[2]) # ๐Ÿ‘‰๏ธ 'c'

When we access the queue item at the specific index on a deque object, the item remains in the queue.

Conversely, if you use the get() method on a queue object or the popleft() or pop() methods on a deque object, the item gets returned and removed from the queue.

# Get the First element of a Queue in Python

You can use the get() method to get the first element of a queue.

The get() method removes and returns an item from the queue.

main.py
import queue q = queue.Queue() for item in range(15): q.put(item) print(q.queue[0]) # ๐Ÿ‘‰๏ธ 0 get first without removing it # ๐Ÿ‘‡๏ธ Remove and return an item from the queue print(q.get()) # ๐Ÿ‘‰๏ธ 0 (get first) print(q.get()) # ๐Ÿ‘‰๏ธ 1 (get second) print(q.get()) # ๐Ÿ‘‰๏ธ 2 (get third)

get first element of queue

The code for this article is available on GitHub

If you don't want to remove the element, use the queue attribute on the queue and access the element at index 0.

If you use deque objects from the collections module, scroll down to the next code snippet.

The queue attribute gives us access to a deque object and deque objects support popleft() operations and indexing.

If you don't want to remove the specific element of the queue and only want to access it, use q.queue[0].

The queue.get() method removes and returns an item from the queue.

If you use the collections.deque class, you can access the first element in the queue by accessing the deque object at index 0.

main.py
from collections import deque deq = deque(['a', 'b', 'c']) print(deq[0]) # ๐Ÿ‘‰๏ธ get first print(deq[1]) # ๐Ÿ‘‰๏ธ get second print(deq[2]) # ๐Ÿ‘‰๏ธ get third first = deq.popleft() print(first) # ๐Ÿ‘‰๏ธ 'a' print(deq) # ๐Ÿ‘‰๏ธ deque(['b', 'c'])
The code for this article is available on GitHub
Deque objects support indexing, so getting the first element of the queue is the same as getting the first element of a list.

Deque objects also support the popleft() method.

The method removes and returns an element from the left side of the deque.

If no elements are present in the deque, the method raises an IndexError.

If you need to remove and return an element from the right side of the deque, use the pop() method.

main.py
from collections import deque deq = deque(['a', 'b', 'c']) print(deq[0]) # ๐Ÿ‘‰๏ธ get first first = deq.popleft() print(first) # ๐Ÿ‘‰๏ธ 'a' print(deq) # ๐Ÿ‘‰๏ธ deque(['b', 'c']) last = deq.pop() print(last) # ๐Ÿ‘‰๏ธ 'c' print(deq) # ๐Ÿ‘‰๏ธ deque(['b'])

# Check if an element is in a Queue in Python

If you need to check if an element is in a queue:

  1. Access the queue attribute on the queue to get a deque object.
  2. Use the in operator to check if the element is in the queue.
  3. The in operator tests for membership.
main.py
import queue q = queue.Queue() q.put(0) q.put(1) if 0 in q.queue: # ๐Ÿ‘‡๏ธ This runs print('0 is in queue') if 100 not in q.queue: # ๐Ÿ‘‡๏ธ This runs print('100 is NOT in queue')

check if element is in queue

The code for this article is available on GitHub

The queue attribute on the queue returns a deque object. Deque objects support indexing and membership testing.

The in operator tests for membership. For example, x in q evaluates to True if x is a member of q, otherwise it evaluates to False.

If you used the collections.deque class to initialize a deque object, you can directly use the in operator to check if an item is in the deque.

main.py
from collections import deque deq = deque(['a', 'b']) if 'a' in deq: print('a is in deque') if 'z' not in deq: print('z is NOT in deque')

The collections.deque class has atomic append(), implements the popleft() method and supports indexing and membership testing.

If you used the queue module, access the queue attribute on the queue to get a deque object.

main.py
import queue q = queue.Queue() q.put(0) q.put(1) print(q.queue) # ๐Ÿ‘‰๏ธ deque([0, 1])

# Put multiple items in a Queue in Python

If you need to put multiple items in a queue:

  1. Use a for loop to iterate over an iterable or a range.
  2. On each iteration call the put() method on the iterable.
  3. Pass the item to the put() method.
main.py
import queue q = queue.Queue() my_list = list(range(10)) print(my_list) # ๐Ÿ‘‡๏ธ Iterate over list and put each item in the queue for item in my_list: q.put(item) print(q.queue) # ๐Ÿ‘‰๏ธ deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) for item in q.queue: print(item) # ๐Ÿ‘‰๏ธ 0 1 2 3 4 ...
The code for this article is available on GitHub

We used a for loop to iterate over a list containing 10 items and used the put() method to put each item in the queue.

The Queue.put() method puts an item in the queue.

You can also use a range if you need to put N items in the queue.

main.py
import queue q = queue.Queue() # ๐Ÿ‘‡๏ธ Iterate over range and put each item in the queue for item in range(10): q.put(item) print(q.queue) # ๐Ÿ‘‰๏ธ deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) for item in q.queue: print(item) # ๐Ÿ‘‰๏ธ 0 1 2 3 4 ...

If you use a deque object, you can pass an iterable directly to the extend() method.

main.py
from collections import deque deq = deque() my_list = list(range(10)) deq.extend(my_list) print(deq) # ๐Ÿ‘‰๏ธ deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) for item in deq: print(item) # 0 1 2 3 4 ...

We used the collections.deque class to create a deque object.

The extend method takes an iterable as an argument and extends the right side of the deque by appending the items from the iterable.

You can also use a for loop with the append() method.

main.py
from collections import deque deq = deque() print(deq) my_list = list(range(10)) for item in my_list: deq.append(item) print(deq) # ๐Ÿ‘‰๏ธ deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) for item in deq: print(item) # ๐Ÿ‘‰๏ธ 0 1 2 3 4 ...

The append() method takes a value and adds it to the right side of the deque.

# Iterate through a Queue in Python

You can use a while loop to iterate through a 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 code for this article is available on GitHub

The loop checks if the queue is not empty and iterates as long as there are items in the queue.

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 code for this article is available on GitHub

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.

# Handle the queue.Empty exception in Python

Use a try/except statement to handle the queue.Empty exception.

main.py
import queue q = queue.Queue() q.get(False) try: item = q.get(False) # ๐Ÿ‘‰๏ธ do work here # ๐Ÿ‘‡๏ธ indicate task complete q.task_done() except queue.Empty: print('queue.Empty exception') # ๐Ÿ‘‰๏ธ handle empty queue exception pass

You can use the get() method in the try block and catch the queue.Empty exception in the except block.

The Queue.get() method removes and returns an item from the queue.

We passed False to the method to make it non-blocking.

If an item is not immediately available in the queue, the method raises a queue.Empty exception.

You can do all the necessary work in the try block and call the Queue.task_done method at the end to indicate that the task is complete.

We can use the task_done() method to tell the queue that the task is complete after each call to the get() method to fetch a task.

# Using an else block

You can also simplify this a bit by using an else block.

main.py
import queue q = queue.Queue() try: item = q.get(False) # ๐Ÿ‘‰๏ธ do work here except queue.Empty: print('queue.Empty exception') # Handle empty queue exception pass else: # ๐Ÿ‘‡๏ธ indicate task complete q.task_done()
The code for this article is available on GitHub

The try/except statement has an optional else clause.

The else block runs only if the try block doesn't raise an exception.

I've also written an article on how to get the length of a Queue.

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.

Copyright ยฉ 2024 Borislav Hadzhiev