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