Member-only story
How to use the assignment expression/walrus operator (:=
) in Python
Learn a cool feature to simplify your Python code
A cool new feature called assignment expression was introduced in PEP572 in Python 3.8. Assignment expression uses operator :=
to assign the value of an expression to a variable. Since operator :=
resembles the eyes and tusks of a walrus, it is informally known as “the walrus operator”.
The assignment expressions are most commonly used in if
and while
conditions to simplify code. While they can also be used in other cases as demonstrated in PEP572, it is recommended not to do so in order to improve code readability and avoid confusion.
The major benefit of assignment expressions is that we can reduce the lines of code when we first need to check the value of some expression and then have some logic for the returned value. A common use case is text-matching by regular expressions. Without using assignment expressions, we need to first get the match
object before we can get the matched value: