Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

W is for walrus operator - Python A to Z

Code in this blog post was written with versions: Python: 3.14

Python A-Z is a blog series about Python. Each day, I share insights, ideas and examples for different parts of Python development that match with the letter of the day. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month.

Often in programming we end up in a situation where we want to check for an output of a function and then do something to it if it’s truthy.

if get_next_step() is not None:
	execute(get_next_step())

To avoid calling the function twice and saving computing cycles, we would then call it first, save it and test against it:

next_step = get_next_step()
if next_step is not None:
  execute(next_step)

In Python 3.8, we got an assignment operator (:=), nicknamed walrus operator because it looks like a cute walrus. It lets us shortcut this with

if (next_step := get_next_step()) is not None:
  execute(next_step)

It’s also handy in loops

while (next_step := get_next_step()) is not None:
  execute(next_step)

Now we skip two assignments: one before the loop for initial check and another at the end of the loop for next check.

It’s a great example of relatively small syntax thing that makes the code cleaner and easier to follow and less error prone.


If something above resonated with you, let's start a discussion about it! Email me at juhis@hamatti.org and share your thoughts. This year, I want to have more deeper discussions with people from around the world and I'd love if you'd be part of that.