Python Tutorials - Herong's Tutorial Examples - v2.14, by Herong Yang
Assignment Expression - Walrus Operation
This section provides a quick introduction on assignment expression, which assigns an object to a variable and returns the object at the same time.
What Is Assignment Expression? An assignment expression is a special expression that assigns an object to a variable and returns the object at the same time.
An assignment expression is also called a walrus operation, because its operator, :=, looks like the eyes and tusks of a walrus on its side.
Assignment expressions are used as operands in other operations as shown in the following example:
# assign 10 to x and continue to add by 5 >>> y = (x := 10) + 5 >>> x 10 >>> y 15
The above example is a valid use of assignment expressions, but it is not good example. It actually makes the Python code harder to read.
Here is a good example of using assignment expressions. It repeatedly reads and processes a 1024-byte chunk of data from a file, until no more data available from the file.
>>> while chunk := file.read(1024): ... process(chunk)
Without using the assignment expression, the above code needs to be rewritten as:
>>> chunk = file.read(1024) >>> while chunk: ... process(chunk) ... chunk = file.read(1024)
Walrus operations have a precedence lower that Ternary operations:
Symbols Operations -------------------- -------------- ... not Boolean NOT and Boolean AND or Boolean OR if ... else Ternary operation := Walrus operation
Note that an assignment expression can not be used by alone as an expression statement. It needs to be enclosed within parentheses.
>>> x := 10 ^ SyntaxError: invalid syntax >>> (x := 10) 10
I think this is to prevent programmer mistakenly writing an assignment statement as an assignment expression.
Table of Contents
►Variables, Operations and Expressions
Conditional Expression - Ternary Operation
►Assignment Expression - Walrus Operation
Function Statement and Function Call
Iterators, Generators and List Comprehensions
Packages and Package Directories
"pathlib" - Object-Oriented Filesystem Paths
"pip" - Package Installer for Python
SciPy.org - Python Libraries for Science
pandas - Data Analysis and Manipulation
Anaconda - Python Environment Manager