Send Close Add comments: (status displays here)
Got it!  This site "robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.  Note: This appears on each machine/browser from which this site is accessed.
Python: Walrus operator
by RS  admin@robinsnyder.com : 1024 x 640


1. Python: Walrus operator
Python 3.8 added a construct called the "walrus operator". This operator, ":=" has some controversy but also some times when it can be useful.

2. Walrus operator
The Python walrus operator ":=" is used inside an expression to assign a subexpression a value - just as in an assignment statement.

Performing a destructive update of a variable in an expression evaluation is usually considered bad programming practice. Correctness rules assume this does not happen. Avoid this usage.

3. Usefulness
Using an assignment in an expression can be useful when the variable there is no destructive update. That is, the variable did not previously have a value used in the program.

Note: In a loop where each loop body is distinct from the rest of the code, reassigning a variable that was only used during the last loop body iteration does not violate this principle.

4. Python program example
Here is a somewhat contrived example to show the concept.

Here is the Python code [#1]

Here is the output of the Python code.


5. Names
The walrus operator is sometimes called the following.

by RS  admin@robinsnyder.com : 1024 x 640