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.


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.

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”:
            	current = input (“Input data: ”)

#walrus #operator #python

How to Use the Walrus Operator in Python
1.40 GEEK