Borislav Hadzhiev
Thu Jun 16 2022·1 min read
Photo by Maria Oliynyk
To check if an element is in a queue in Python:
queue
attribute on the queue to get a deque
object.in
operator to check if the element is in the queue.in
operator tests for membership.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
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.
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.
import queue q = queue.Queue() q.put(0) q.put(1) print(q.queue) # 👉️ deque([0, 1])