2

Hoping someone can explain what's going on with this while loop.

x=deque([(1,2,3)])
while x:
    a,b,c = x.popleft()
    do stuff with values in x
    x.append((d,e,f))

I get that x is a deque with 3 items which are constantly being replaced by new values. But I've never encountered a while loop without some kind of condition. How will the loop know when to stop?

martineau
  • 119,623
  • 25
  • 170
  • 301
gsm113
  • 41
  • 1
  • 4
  • 4
    everything in python has it boolean value. So do `deques`. They return `False` when empty. Thats your exit condition. Having said that, there are such loops (at least sort of) that look like this: `while True:`. These loops can only be terminated from the inside using `break`! – Ma0 Nov 22 '16 at 14:58
  • 2
    Also note that your deque has not three, but just one element (being a tuple of three), and the loop will probably never stop, as `x` can never be empty with that `x.append` at the end (unless there is a `break` or `continue` in the omitted code) – tobias_k Nov 22 '16 at 15:04
  • Also note that the loop is *infinite* for the reasons stated in @ Hettinger's [answer](https://stackoverflow.com/a/58679920/355230) – martineau Aug 23 '21 at 07:56

2 Answers2

1
x=deque([(1,2,3)]) # create new deque
while x: # while not empty
    a,b,c = x.popleft() # pop values and assign them to a and b and c
    # do stuff with values in x - this is comment too
    x.append((d,e,f)) # assumes produced new values d 
                      #and e and f and pushes them to x
# this assumes there is always d and e and f values and stays forever in loop 

as explained in How to check if a deque is empty?

martineau
  • 119,623
  • 25
  • 170
  • 301
obayhan
  • 1,636
  • 18
  • 35
  • 2
    the `do stuff with values in x` is probably where the `d`, `e` and `f` come from. So it is not exactly a comment but rather pseudocode. That is my undertanding at least – Ma0 Nov 22 '16 at 15:06
1

As written, the code is an infinite loop because it adds data at the same rate as it is being removed.

If the size was being whittled down, the while x would terminate the loop when the deque was empty.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485