How to Use the Walrus Operator in Python
In this article, I will talk about the walrus operator in Python.
The biggest change in Python is the introduction of assignment expressions, also known as walrus operator.
Assignment expression can be defined as a Python expression that allows you to assign and return a value in the same expression.
Table of Contents
You can skip to a specific section of this walrus operator tutorial using the table of contents below:
Notation
Walrus operator looks like this:
NAME := expr
It is called the walrus operator because it looks like the eyes and tusks of a walrus on its side (:=). Now, if you want to assign a value to a variable and return it within the same expression, you can use assignment expression. Here is an example of how that is done typically in Python:
walrus = True
print(walrus)
This program will return True
.
However, these two statements can be combined to form one statement using the walrus operator. Here’s how to do that:
print(walrus := True)
This program again will return True
. You can clearly see that using assignment expression you are able to assign True
to walrus and print it immediately. You do not need a separate statement to do that. However, you must understand that you cannot use the walrus operator to do something that is not possible without it.
However, you must understand that you cannot use the walrus operator to do something that is not possible without it. The whole idea behind a walrus operator is only to make some constructs more convenient or to communicate the intent of your code with greater clarity.
Strength of Walrus Operator – Demonstrated in While Loop
I will now demonstrate the use of assignment expressions in a while loop. In a while
loop, a variable is initialized and updated. Look at the program below. Here the code requires the user to keep inputting data until they type end
.
inputs = list ()
current = input (“Input data: ”)
while current != “end”:
inputs.append(current)
current = input (“Input data: ”)
This code is not perfect and it can be made more efficient by setting up an infinite while
loop and using break
to stop it.
input = list ()
while True:
current = input (“Input data: ”)
if current == “end”:
break
input.append(current)
However, using walrus operator this can be done quite easily and it also simplifies the code to a large extent:
input = list ()
while (current := input (“Input data: ”))!= “end”:
inputs.append(current)
Final Thoughts
Assignment expressions are more about making the code simple by condensing it so that you do not have to use four lines for what can be achieved in two. There is no specific function that it performs, and therefore, only the code that runs without a walrus operator can be run using it.
If you're interested in learning more about the functionality (and controversy) of the walrus operator, I would highly recommend this fascinating video from Lex Fridman: