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.
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")
count = 0
while (count := count + 1) < 5:
pass
print("count after loop:", count)