Python Walrus Operator in While Loops
Asked Answered
C

2

21

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
Concentrate answered 30/12, 2020 at 22:51 Comment(2)
x := True is evaluated at the top of the loop, every time the top of the loop is reached. So the value of x tested is always True. x = False was not ignored. x := True changes the binding of x to True regardless of what x was bound to.Subtlety
Got it! too bad. I really wanted that to work! hehe.Solicitude
Q
34

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.

Questor answered 30/12, 2020 at 22:54 Comment(2)
I'm legitimately curious: what is bringing people to this question? Is there a common misconception that := will only execute once when used in a condition, or is it for unrelated issues? If it's the latter, I almost feel like the question could be "repurposed" to be a better use of the traffic.Questor
The first time I ever visited this question, it was the former. Now, it is the latter. @QuestorPressmark
P
6

Let's assume we have a code:

>>> a = 'suhail'
>>> while len(a) < 10:
...   print(f"too small {len(a)} elements expected at least 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 at least 10")
...   a += '1'
... 
too small 6 elements expected at least 10
too small 7 elements expected at least 10
too small 8 elements expected at least 10
too small 9 elements expected at least 10
Premiere answered 28/9, 2021 at 23:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.