Python Walrus Operator in While Loops

Viewed 4672

I'm trying to understand the walrus assignment operator.

Classic while loop breaks when condition is reassigned to False within the loop.

x = True
while x:
    print('hello')
    x = False

Why doesn't this work using the walrus operator? It ignores the reassignment of x producing an infinite loop.

while x := True:
    print('hello')
    x = False
2 Answers

You seem to be under the impression that that assignment happens once before the loop is entered, but that isn't the case. The reassignment happens before the condition is checked, and that happens on every iteration.

x := True will always be true, regardless of any other code, which means the condition will always evaluate to true.

lets assume we have a code:

>>> a = 'suhail'
>>> while len(a)<10:
...  print(f"too small {len(a)} elements expected atleast 10")
...  a+='1'

the assignment expression helps avoid calling len() twice:

>>> a='suhail'
>>> while (n:=len(a))<10:
...  print(f"too small {n} elements expected atleast 10")
...  a+='1'
... 
too small 6 elements expected atleast 10
too small 7 elements expected atleast 10
too small 8 elements expected atleast 10
too small 9 elements expected atleast 10
Related