Should You Be Using Python’s Walrus Operator? (Yes. And Here’s Why)

Martin Heinz on 2022-07-03

Python’s controversial assignment expression — known as the walrus operator — can improve your code, and it’s time you start using it!

Photo by Jonathan Cooper on Unsplash

The assignment operator — or walrus operator as we all know it — is a feature that’s been in Python for a while now (since 3.8), yet it’s still somewhat controversial, and many people have unfounded hate for it.

In this article, I will try to convince you that the walrus operator really is a good addition to the language and that if you use it properly, then it can help you make your code more concise and readable.

Basics/Essentials

In case you’re not yet familiar with the :=, let's first review some of the basic use cases that might persuade you to give this Python feature a shot.

The first example I want to show you is how you can use the walrus operator to reduce the number of function invocations. Let’s imagine a function called func() that performs some very expensive computations. It takes a long time to compute results, so we don't want to call it many times. Here’s how you do this:

walrus_repeated_calls.py

# "func" called 3 times
result = [func(x), func(x)**2, func(x)**3]

# Reuse result of "func" without splitting the code into multiple lines
result = [y := func(x), y**2, y**3]

In the first list of the declaration above, the func(x) is called three times, every time returning the same result, which wastes time and computing resources. When rewritten using the walrus operator, func() is invoked only once, assigning its result to y and reusing it for the remaining two list values.

You might say, "I can just add y = func(x) before the list declaration, and I don't need the walrus!" Yes, you can, but that's one extra, unnecessary line of code, and at first glance — without knowing that func(x) is super slow — it might not be clear why the extra y variable needs to exist.

If you’re not convinced by the above, I have another one. Consider the following list comprehensions with the same expensive func():