Since Python 3.8, code can use the so-called "walrus" operator (:=
), documented in PEP 572, for assignment expressions.
This seems like a really substantial new feature, since it allows this form of assignment within comprehensions and lambda
s.
What exactly are the syntax, semantics, and grammar specifications of assignment expressions?
Why was this new (and seemingly quite radical) concept introduced, even though PEP 379 (which proposes the similar idea of "Adding an assignment expression") was withdrawn?
In simple terms := is a expression + assignment operator. it executes an expression and assigns the result of that expression in a single variable.
simple useful case will be to reduce function calls in comprehensions while maintaining the redability.
lets consider a list comprehension to add one and filter if result is grater than 0 without a := operator. Here we need to call the add_one function twice.
Case 1:
The result is as expected and we don't need to call the add_one function to call twice which shows the advantage of := operator
be cautious with walarus := operator while using list comprehension
below cases might help you better understand the use of := operator
Case 2:
Case 3: when a global variable is set to positive
Case 4: when a global variable is set to negitive