Glossary

Walrus Operator

Also known as: assignment expression, :=

The walrus operator (:=, formally called the "assignment expression", PEP 572, Python 3.8) assigns a value to a variable as part of a larger expression. It lets you compute a value, bind it to a name, and use that name — all in one expression. The name "walrus" comes from the operator's visual resemblance to a walrus turned sideways.

The most common use case is avoiding redundant computation in while loops and if statements. For example, instead of line = f.readline() followed by while line:, you can write while (line := f.readline()):. Similarly, if (m := re.search(pattern, text)): computes the match and checks it in one step, with m available inside the if block.

The walrus operator was one of the most controversial additions to Python. Guido van Rossum's insistence on accepting PEP 572 over significant community opposition was a factor in his decision to step down as BDFL (Benevolent Dictator For Life). The style guideline is to use := only when it genuinely improves readability by eliminating duplication — not as a general replacement for regular assignment statements.

Related terms: Conditional Statement, While Loop

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.