Mastery
Mastery/Python/E. Typing & modern syntax
T1 · high-leverage

The walrus operator :=

:= assigns and produces the assigned value in the same expression -- most useful for avoiding a duplicated call, or for while loops whose condition IS the thing you want to use. One genuinely subtle scoping rule: inside a list/set/dict comprehension, the comprehension's own loop variable stays local to it as always, but a walrus target leaks into the enclosing scope -- deliberately, by design (PEP 572), specifically so you can use it after the comprehension ends.

python
data = [1, 2, 3, 4, 5, 6, 7, 8]

# without walrus you'd compute x*x twice (once to filter, once to use) or use a helper -- this does it once:
results = [y for x in data if (y := x * x) > 20]
print("filtered squares:", results)
print("the walrus target leaks OUT of the comprehension:", y, " <- still accessible here, by design")
python
count = 0
while (count := count + 1) < 5:
    pass
print("count after loop:", count)

Interview angle

Less a trick question than a "read recent code" fluency check — candidates unfamiliar with := sometimes misread it as a typo for = or == the first time they see it. A good follow-up is the comprehension-scoping question: does the walrus target leak out of a list comprehension? (Yes, deliberately — unlike the comprehension's own loop variable.) That's a specific, testable detail that separates "seen it before" from "understands it."

In the industry

The walrus shows up most often in exactly two idioms: while (chunk := f.read(size)):-style read loops, and filtering a comprehension on a value you also want to keep, without computing it twice. Style guides are mixed on encouraging it broadly — used well it removes real duplication, used poorly it makes a line harder to read at a glance — so most teams' guidance is "fine for the read-loop and filter-and-keep idioms, otherwise prefer a separate assignment."