SyntaxStudy
Sign Up
Python Walrus Operator in Comprehensions
Python Advanced 4 min read

Walrus Operator in Comprehensions

Walrus Operator in Comprehensions

The walrus operator := (Python 3.8+) lets you assign and use a value in one expression, avoiding repeated computation inside comprehensions.

Example
results = [y for x in range(10) if (y := x**2) > 10]
print(results)
# [16, 25, 36, 49, 64, 81]
Pro Tip

Walrus avoids calling the same expensive function twice in filter + transform.