Python 3.8 introduces assignment expressions affectionately known as “the walrus operator”. That's because the operator looks like a walrus!
The walrus is a large flippered marine mammal with a discontinuous distribution about the North Pole in the Arctic Ocean and subarctic seas of the Northern Hemisphere. — Wikipedia
:=
A use case for this operator is when you want to assign a value to a variable in just one line of code if an initial
boolean expression is True
.
hasCoupon and (discount := 20)
In this example, a 20% discount will be applied if the user has a coupon. The assignment must be inside parentheses here otherwise you will get a syntax error.
discount = 0
hasCoupon = False
hasCoupon and (discount := 20)
print(discount) # output is 0
hasCoupon = True
hasCoupon and (discount := 20)
print(discount) # output is 20
Another motivating use case is where the operator helps to avoid calling a function twice e.g. len
.
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")