What Is the Walrus Operator in Python?

Learn how to condense your code with the new operator released in version 3.8

Jonathan Hsu
Nov 11 · 2 min read

A new operator :=, pleasingly named the walrus operator—see the eyes and tusks— is known as an assignment expression.

The purpose of the walrus operator is to consolidate an assignment statement and a boolean expression when both assignment and expression would utilize a similar statement.

Before and After: Implementing the Walrus Operator

Let’s take a look at a simple use case and how we can implement the walrus operator to improve the efficiency of our code.

We’re going to check the length of a given list and print an error message that includes the length.

In case you’re unsure about the f before the string in the print statement, that’s called a format-string literal, f-string for short.

Now, the walrus operator will eliminate calling the len() function twice.

The type of operator (assignment expression) should give you a hint about what is happening here. The inner-most statement is an assignment n = len(my_list) then the value of n is used in the outer expression.

Don’t Forget the Parenthesis

Python isn’t known for requiring parenthesis very often, but in this case, they are critical for the statement to evaluate properly. To see the results of forgetting the parenthesis, let’s compare each by printing n.

Notice that without the parenthesis, the evaluation of len(my_list) > 3 is assigned.

How Will You Use This?

The walrus operator, allowing a compound assignment expression, opens up a host of new possibilities.

The introduction of this operator has also come with its fair share of criticism, but to me, it’s simply another tool in the kit that can be used when appropriate.

So, will you be using the walrus operator? If so, how will you be using it?

Better Programming

Advice for programmers.

Jonathan Hsu

Written by

I’m a black belt problem-solver (literally). I enjoy the taking on new challenges, building skills, and sharing what I’ve learned. 🥋

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade