Walrus Operator (:=)
Walrus Operator (:=)
Section titled โWalrus Operator (:=)โWhat it is
Section titled โWhat it isโThe walrus operator (:=) allows assignment within expressions, introduced in Python 3.8 (2019). It assigns values while using them in the same expression.
Before this feature
Section titled โBefore this featureโHad to assign before using:
# Assign then useline = input("Enter: ")if line: print(f"You entered: {line}")
# Repeat expressiondata = get_data()if data: process(data)
# Loop requires extra variablematch = re.search(pattern, text)while match: handle(match) match = re.search(pattern, text)After this feature
Section titled โAfter this featureโAssign and use in one expression:
# Inline assignment in ifif (line := input("Enter: ")): print(f"You entered: {line}")
# Avoid repeating function callif (data := get_data()): process(data)
# Cleaner loopswhile (match := re.search(pattern, text)): handle(match) text = text[match.end():]
# List comprehension with intermediate valuevalues = [1, 2, 3, 4, 5]squares = [(x, y) for x in values if (y := x ** 2) > 10]# [(4, 16), (5, 25)]
# Avoid redundant computationdata = [10, 20, 30, 40]if (n := len(data)) > 5: print(f"Large dataset: {n} items")else: print(f"Small dataset: {n} items")
# Read file in chunkswith open('file.txt', 'rb') as f: while (chunk := f.read(1024)): process(chunk)
# Parse and validateimport reif (match := re.match(r'(\d+)-(\d+)', "123-456")): start, end = match.groups() print(f"Range: {start} to {end}")Why this is better
Section titled โWhy this is betterโ- Concise: Combines assignment and use
- DRY: Avoid repeating expressions
- Readable: Intent is clear (when not overused)
- Efficient: Compute once, use multiple times
- Scoping: Variable available in scope
Key notes / edge cases
Section titled โKey notes / edge casesโ- Parentheses required in most contexts
- Variable scope follows normal rules
- Canโt use in lambda (without parentheses around entire lambda)
- Donโt overuse (readability matters)
- Not the same as
==(assignment, not comparison)
# Parentheses required# if x := 5: # SyntaxErrorif (x := 5): # OK print(x)
# Scopeif (x := 10): print(x) # 10print(x) # 10 - still in scope
# List comprehension scope[x for x in range(10) if (y := x * 2) > 5]# y is NOT accessible here (comprehension scope)
# Don't confuse with ==if (x := 5): # Assignment print("x is assigned")
if x == 5: # Comparison print("x equals 5")
# Bad: too complex# DON'T DO THISif (data := get_data()) and (processed := process(data)) and (valid := validate(processed)): save(valid)# Better: multiple statementsQuick practice
Section titled โQuick practiceโ-
Rewrite using walrus:
n = len(items); if n > 0: print(n)Answer
if (n := len(items)) > 0:print(n) -
Use walrus to read lines from a file until empty line
Answer
while (line := input()):print(line) -
When should you avoid the walrus operator?
Answer
When it reduces readability, creates overly complex expressions, or when simple separate statements are clearer.