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
Python 3.8 introduced a new walrus operator := . The name of the operator comes from the fact that is resembles eyes and tusks of a walrus of its side. The walrus operator creates an assignment expression. The operator allows us to assign a value to a variable inside a Python expression.
Assignment expression are written with a new notation (:=) . This operator is often called the walrus operator as it resembles the eyes and tusks of a walrus on its side. The assignment expression allows you to assign True to walrus , and immediately print the value.
There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.
The walrus operator was implemented by Emily Morehouse, and made available in the first alpha release of Python 3.8.
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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With