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:
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:
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.
current =input(“Input data: ”)while current != “end”:
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.
current =input(“Input data: ”)if current == “end”:breakinput.append(current)
However, using walrus operator this can be done quite easily and it also simplifies the code to a large extent:
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: