Walrus operator (:=) — assignment inside an expression (Python 3.8+).
1# Without walrus2data = get_data()3if data:4 process(data)56# With walrus7if data := get_data():8 process(data)910# In loop11while chunk := file.read(1024):12 process(chunk)1314# In list comprehension15results = [y for x in data if (y := expensive(x)) > 0]1617# In condition18if (n := len(items)) > 10:19 print(f"Too many items: {n}")2021# With regex22import re23if match := re.search(r"\d+", "abc123def"):24 print(match.group()) # "123"
Advantages: