Check if an element is in a Queue in Python

avatar

Borislav Hadzhiev

Last updated: Jun 16, 2022

banner

Photo from Unsplash

Check if an element is in a Queue in Python #

To check if an element is in a queue in Python:

  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')

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