PEP 572: The Walrus Operator - Assignment Expressions in Python
TL;DR
PEP 572 introduced the walrus operator (:=) in Python 3.8, allowing assignment within expressions to reduce code duplication and improve readability.
Interesting!
The walrus operator gets its name from its resemblance to a walrus face - the colon represents the eyes and the equals sign represents the tusks!
Assignment Within Expressions
python code snippet start
# Before - repetitive code
if len(data) > 10:
process(data)
# After - with walrus operator
if (n := len(data)) > 10:
process_with_length(data, n)
python code snippet end
Common Use Cases
python code snippet start
# List comprehensions
squares = [square for x in numbers if (square := x**2) > 10]
# While loops
while chunk := file.read(1024):
process_chunk(chunk)
python code snippet end
The walrus operator eliminates redundant computations and makes code more concise while maintaining readability.
The walrus operator pairs particularly well with itertools functions and control flow patterns for more expressive code.
Reference: PEP 572 - Assignment Expressions