The Walrus Operator (:=) in Practice
The walrus operator (:=) assigns values to variables as part of an expression. Introduced in Python 3.8, it solves a longstanding annoyance: the inability to assign inside conditions, comprehensions, and other expression contexts where statements are not allowed.
What It Does
The walrus operator lets you assign to a variable and return the assigned value in a single expression. The syntax name := value assigns value to name and then evaluates to that value.
The name comes from its resemblance to the eyes and tusks of a walrus. This operator was one of the most requested features before its introduction.
# Without walrus - calculate twice
result = some_function()
if result:
print(result)
# With walrus - calculate once
if (result := some_function()):
print(result)
List Comprehensions
The walrus operator shines in list comprehensions where you need to use a computed value multiple times:
# Without walrus - compute len() twice
words = ["hello", "world", "foo", "bar"]
long_words = [w for w in words if len(w) > 3 and len(w) < 10]
# With walrus - compute len() once
long_words = [w for w in words if (n := len(w)) > 3 and n < 10]
This avoids redundant calculations and keeps comprehensions cleaner. You can store any intermediate result this way, not just lengths. The same applies to filtering and transforming data where an expensive operation would otherwise be repeated.
While Loops
In while loops, the walrus operator lets you read and assign in the condition itself:
# Without walrus - read before loop, check in condition
line = file.readline()
while line:
process(line)
line = file.readline()
# With walrus - read and assign in one place
while (line := file.readline()):
process(line)
This pattern is cleaner since the assignment happens right where you need it. It is sometimes called the “loop-and-a-half” pattern. You avoid the awkward setup before the loop and keep everything in one place.
Conditional Assignment
You can use walrus in ternary expressions and other conditional contexts:
# Assign only if condition is true
data = (cached := get_data()) if should_cache else default_value
# Use in min/max calls
winner = max(scores, key=lambda x: (score := get_score(x)))
# Chaining operations
result = (parsed := json.loads(text)) and process(parsed)
The walrus operator works anywhere an expression is allowed, giving you flexibility in how you structure conditional logic.
Debugging Comprehensions
One handy use case is adding debug prints inside comprehensions without refactoring:
# Print intermediate results while filtering
results = [x for x in items if print(f"Checking {x}") or x > threshold]
This technique helps you understand what is happening inside complex comprehensions. It is useful when debugging why certain items are or are not included in your results.
Scope Considerations
The walrus operator follows Python’s normal scoping rules. Variables assigned with := are available in the enclosing scope. However, be careful in comprehensions—the variable leaks to the surrounding scope, which can cause unexpected behavior:
[x := i for i in range(5)] # i is now 4 in the outer scope
print(i) # Prints 4
This is different from loop variables in classic for loops, which do not leak.
Why It Was Added
Before Python 3.8, you could not assign inside expressions. This forced awkward patterns: pre-assigning variables before conditions, computing values multiple times, or refactoring into separate loops. The walrus operator brings assignment into expression contexts, making code more concise and avoiding repeated computations.
Common Use Cases
- Avoiding repeated method calls - call once, store result
- Loop-and-a-half pattern - read in while condition
- Debugging comprehensions - print intermediate values
- Caching in expressions - store expensive computations
- Regex matching - capture and use groups in one expression
See Also
- List Comprehensions — Master the syntax for creating lists
- F-Strings Guide — Format strings with embedded expressions
- Python Operators Reference — Complete operator reference