Member-only story

How to use the assignment expression/walrus operator (:=) in Python

Learn a cool feature to simplify your Python code

Lynn G. Kwong
3 min readMay 23, 2021

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”.

Photo by Jay Ruzesky on Unsplash.

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:

--

--

Lynn G. Kwong
Lynn G. Kwong

Written by Lynn G. Kwong

I’m a Software Developer (https://youtube.com/@kwonglynn) keen on sharing thoughts, tutorials, and solutions for the best practice of software development.

No responses yet