How to Use Assignment Expressions in Python
Many languages support assignment expressions, and with version 3.8 (PEP 572), Python is joining the party. Assignment expressions allow us to name the result of expressions, which results in cleaner, more concise code.
Previously, this was only possible in statement form, like this:
n = 4
result = n * n # <= naming the expression result was only possible in statement form
if result > 10:
print(result)
Assignment expressions, however, allow us to avoid the statement, and assign the value of result
right in the conditional expression.
n = 4
if (result := n * n) > 10:
print(result)
Why is is called the "walrus operator"?
Well, because it looks like a walrus! :=
Now that we've covered the basics, I'll provide some examples where assignment expressions might prove useful.