Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Core language & syntaxMiddleCommonTheory

What does the walrus operator (`:=`) do, and where does it help avoid repeated computation?

Answer

The walrus operator, introduced by PEP 572 in Python 3.8, assigns a value to a name as part of a larger expression instead of requiring a separate statement, and the expression evaluates to that same value. It is most useful in `while` loop conditions, comprehensions and `if` conditions where the same value would otherwise need to be computed twice: once to check it and once to use it.

Strong answer includes

  • assignment as part of an expression
  • introduced by PEP 572 in 3.8
  • avoids computing a value twice

Practical example

Python example
while (chunk := file.read(8192)):

reads and assigns in one step, replacing the older pattern of reading before the loop and again at the end of the loop body.

#syntax#pep-572

Sources

PEP 572 — Assignment ExpressionsPython Software Foundation · The walrus operator and its scoping rulesWhat's new in Python 3.14Python Software Foundation · Current-version language and runtime changes, including template strings and free-threading support