Python’s Walrus Operator

2 min readNov 25, 2021

The Walrus operator was introduced to Python in 3.8, here is a quick overview of the operator and how you can use it.

The Walrus that was added to python3.8

The Walrus operator := goal is to allow a user to name variables and use them
in expressions with ease. It takes the form of NAME := expr. Below is an

while data :=

In this example, each time the while loop is run, data will be set to the output
of until there is no data left to read. Each loop will run
the process function on each 1024 chunk of data. While this is a super simple
example, it shows that you can assign the output of an expression to a variable in the while expression.

This Operator also allows a user to reuse an expression in the case of regex

import re
pattern = re.compile(“foo”)
if (match :=“This is just foobar”)) is not None:

We are saving one line of code by using the walrus operator, as you can see
here. Since an alternative way of writing this is:

import re
pattern = re.compile(“foo”)
match =“This is just foobar”)
if match is not None:

Obviously, in real-world examples, you would be doing more than just printing.


This was originally posted on my personal blog:




A collection of my learnings in all things Python, AI, MLOPS, NLP, Software engineering, and Bug Bounty Hunting.