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

 About This Book

 Running Python Code Online

 Python on macOS Computers

 Python on Linux Computers

 Built-in Data Types

Variables, Operations and Expressions

 What Is Variable

 What Is Operation

 What Is Expression

 Conditional Expression - Ternary Operation

Assignment Expression - Walrus Operation

 Statements - Execution Units

 Function Statement and Function Call

 Iterators, Generators and List Comprehensions

 Classes and Instances

 Modules and Module Files

 Packages and Package Directories

 "sys" and "os" Modules

 "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

 Jupyter Notebook and JupyterLab

 References

 Full Version in PDF/EPUB