Sitemap
The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K followers.

Walrus Operators in Python

5 min readMar 6, 2020

--

Assignment expressions are a new feature added in Python 3.8. They allow you check a value and assign it to a variable in one expression, simplifying many for and while constructs

The operator is := which looks like the eyes and tusks of a walrus, hence its name, the walrus operator.

Press enter or click to view image in full size

Example

Here is a simple code fragment that prints the length of a string s, but only if the string is longer than 5:

if len(s) > 5:
print(len(s))

That is ok, but it calls len(s) twice, which isn't ideal. Repeated code is best avoided where possible from the point of view of readability, and of course it can be inefficient to make unnecessary function calls.

The standard way to avoid this would be:

x = len(s)
if x > 5:
print(x)

This solves the problem but adds an extra line to your code.

The walrus operator allows you to do this:

if (x := len(s)) > 5:
print(x)

The := operator assigns the value of len(s) to the variable x, but still allows us use the result in the comparison expression.

Assignment expressions

Until 3.8, assignment in Python could only be done via assignment statements like…

--

--

The Startup
The Startup

Published in The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K followers.