Assigning Values to Variables as Part of a Larger Expression in Python 3.8

Python1 min readJune 17, 2020

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

Walrus operator


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)")

Copyright © 2006 - 2021 Vahid Hallaji
The content and codes are open source and published under the CC BY-SA and MIT licences respectively unless otherwise noted.
If you find anything you can improve, please feel free to submit an issue or a pull request.
Built with Nextjs and deployed by Vercel.