First Things First!
Explore how to use Python's Walrus operator introduced in version 3.8 to assign values within expressions effectively. Understand syntax rules and limitations like parenthesizing restrictions and why some forms cause errors. This lesson helps you write cleaner, more concise code using assignment expressions.
We'll cover the following...
Python 3.8’s “Walrus” operator (:=) was quite popular. Let’s check it out.
Explanation
The Walrus operator (:=) was introduced in Python 3.8, it can be useful in situations where you’d want to assign values to variables within an expression. For instance:
This saved one line of code, and implicitly prevented invoking some_func twice. Now coming back to an explanation of the snippets:
-
Non-parenthesized “assignment expression” (use of the walrus operator) is restricted at the top level, hence the
SyntaxErrorin thea := "ftw_walrus"statement of the code above. Parenthesizing it worked as expected and assigneda. -
As usual, parenthesizing an expression containing the
=operator is not allowed. Hence, there will be a syntax error in(a, b = 6, 9).
-
The syntax of the Walrus operator is of the form
NAME:= expr, whereNAMEis a valid identifier, andexpris a valid expression. -
Hence, iterable packing and unpacking are not supported, which means that
(a := 6, 9)is equivalent to((a := 6), 9), and ultimately to(a, 9)(wherea's value is6).
- Similarly,
(a, b := 16, 19)is equivalent to(a, (b := 16), 19), which is nothing but a 3-tuple.