PEP 572 in 90 seconds — the walrus that ate your for-loop
Assignment as an expression — 3 lines become 1.
You've written this pattern a hundred times: call a function, store the result, check if it's worth using. Three lines. The walrus `:=` does all three in one. Once you see it, you can't unsee it — and you'll start using it in `while` loops, list comprehensions, and `if` checks where you used to need a temporary variable.
Quick reading guide: `:=` is called the walrus operator because the symbol looks like a walrus's eyes and tusks 🦭. It binds a name AND returns the value in a single expression. Ships in Python 3.8 (Oct 2019). The PEP itself was so controversial that Guido van Rossum stepped down as BDFL right after accepting it — the trick is small, the political fight was big.
# Compute first, then check
data = fetch_data()
if data is not None:
print(f"Got {len(data)} items")
# Or in a while loop — even uglier
while True:
chunk = stream.read(1024)
if not chunk:
break
process(chunk)# Bind AND check in one expression
if (data := fetch_data()) is not None:
print(f"Got {len(data)} items")
# While loop — clean
while chunk := stream.read(1024):
process(chunk)🎯 Predict the output
What does this print?
numbers = [10, 20, 30, 40, 50]
if (n := len(numbers)) > 3:
print(f"long list ({n})")
else:
print(f"short ({n})")
print(n)