Member-only story
The Walrus Operator in Python
Learn what the walrus operator is and how to use it in Python
The walrus operator, introduced in Python 3.8, offers a way to accomplish two tasks at once: assigning a value to a variable, and returning that value, which can sometimes offer a way to write shorter, more readable code, that may even be more computationally efficient.
Let’s review what the walrus operator is and some examples of when it can be useful.
simple assignment operator
We are all familiar with how to assign a value to a variable. We do so using the simple assignment operator:
num = 15
And if we wanted to print the value of this variable using the print function, we can pass in the variable num as follows:
print(num)
# 15
enter the walrus operator
Introduced in python 3.8, the walrus operator, (:=), formally known as the assignment expression operator, offers a way to assign to variables within an expression, including variables that do not exist yet. As seen above, with the simple assignment operator (=), we assigned num = 15 in the context of a stand-alone statement.
An expression evaluates to a value. A…