-1

I am trying to loop through a Queue from the queuemodule in python, I dont want to empty the queue, I dont know how. This is my code.

from queue import Queue
q = Queue()
q.put(3)
q.put(5)
q.put(7)
for element in q:
    print(element)

How can I do this? The error messange is: TypeError: 'Queue' object is not iterable I want to use Queue, because Im using it for BFS. I cant empty the Queue.

Flavio
  • 73
  • 7

1 Answers1

2

Try using q.queue:

from queue import Queue

q = Queue()
q.put(3)
q.put(5)
q.put(7)

for element in q.queue:
    print(element)

Output:

3
5
7

Note you may want to consider using collections.deque instead.

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
  • You have solved my problem. – Flavio May 29 '22 at 15:52
  • 1
    Why would I use collections.deque instead, whats the problem with queue.Queue() – Flavio May 29 '22 at 15:52
  • 2
    See this answer: https://stackoverflow.com/a/717261/6328256, also `q.queue` is a deque anyway. – Sash Sinha May 29 '22 at 15:53
  • Keep in mind that the `queue` attribute is not documented, and is not intended to be used directly. A queue isn't designed to be iterated over: it provides constant-operations to inserting and deleting at one (not necessarily the same) end of the queue (and in the case of the `queue` module, thread safety). – chepner May 29 '22 at 17:31