Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Walrus Operator in While Loops

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
like image 441
Le_Prometheen Avatar asked Dec 30 '20 22:12

Le_Prometheen


People also ask

How do you use the walrus operator in Python?

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.

How does the walrus operator look in Python?

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.

What does := mean in Python?

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.

When was the walrus operator introduced Python?

The walrus operator was implemented by Emily Morehouse, and made available in the first alpha release of Python 3.8.


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 happens on every iteration.

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

like image 55
Carcigenicate Avatar answered Sep 20 '22 04:09

Carcigenicate


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
like image 22
suhailvs Avatar answered Sep 23 '22 04:09

suhailvs