Python SnakeBytes: The Walrus Operator

Jason C. McDonald - Oct 21 '19 - - Dev Community

The assignment expression, also known as the walrus operator (:=), was introduced in Python 3.8. An assignment expression performs assignment, while also returning the assigned value from the expression. This allows you to store and test a value in the same line.

temps = [56, 72, 65, 77, 73]

if ((average := sum(temps) / len(temps)) > 80):
    print("It sure is warm!")
elif (average < 50):
    print("It's quite cold.")
else:
    print("Nice weather we're having.")
Enter fullscreen mode Exit fullscreen mode

The average variable was defined within the if expression, so it can be reused in the elif.

When used in a comparison, it may be necessary to wrap the assignment expression in parentheses, as seen here. Otherwise, the result of the comparison will be stored.

But always remember: readability matters. Only use the walrus operator if it will actually make the code more readable. My use of the operator in the example would probably only be justifiable if I don't intend to reuse the average variable outside of the conditional.


PEP 572: Assignment Expression

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player