Get an item from a Queue in Python without removing it

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

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
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.

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.