'What is the difference between (while queue) and (while not queue.empty()) in Python3
I found the difference between
while queue and while not queue.empty() in python3
I thought these are the same, but it wasn't.
when I used
While queue : -> after I used all items in the queue, It just stopped. (No errors)
On the other hand, when I used
While not (queue.empty()): -> it worked as what I thought.
Is there any difference? Or there was something I did wrong?
Thank you!
Solution 1:[1]
while queue: will keep looping forever since it's only checking that queue object isn't None. It doesn't care whether it's empty or not, just that the object exists.
For example:
from queue import SimpleQueue
q = SimpleQueue()
while q:
print ("Queue empty? ", q.empty())
The above script will print "Queue empty? True" infinitely.
Solution 2:[2]
You can also do like:
from queue import Queue
q = Queue(maxsize = <maxsize as per your concern>)
while not q.empty():
print("Queue empty: ", q.empty())
q.get() #to avoid infinite loop
As per your question, the same followed for me and this was the way I cleared it out so clearly they both are different.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Loocid |
| Solution 2 | Muhammad Mohsin Khan |
