ASSIGNMENT EXPRESSION (WALRUS OPERATOR) IN PYTHON

ASSIGNMENT EXPRESSION – Python Walrus Operator

Now, we are going to have a look at a very interesting feature in python, which is assignment expression and is also called a walrus operator (maybe you will soon understand why is it called a walrus operator).

So, what is an assignment expression, or walrus operator? Let’s have a look at this first.

Basically, the walrus operator allows us to assign the value to some variable, as a part of a larger expression. Simply put, it is a way to assign values to variables within an expression. When we will have some examples, things would get clearer.

But even before we get into the examples, Let’s have a look at what the walrus operator looks like. It basically is a colon, followed by an equals sign (:=).

Python Walrus Operator

Now, Let’s have a look at a program, which would not use the walrus operator here. In the below program, we are not doing much. We are just checking whether or not the given number is even or odd. So, Let’s have a look at this now –

In the above program, as you can see, we have a number, and we are checking whether the number is even or odd. In our case, the number is even. But here, if you observe, we are assigning the value to the variable first, and then we are checking the condition, and then we are giving the output accordingly. What if we could make it a little bit shorter? What if we could assign the value to the variable within the expression where we are checking if the number is divisible by 2? Well, I mean something like this –


Here, as a part of the expression, we are also assigning the value to the variable. But here, we are getting an error, because we have not used the walrus operator. Just in the place of that equal to sign, we have to use the walrus operator, and we are done. Let’s have a look –

Now, as you can see, we got the walrus operator used here. What is happening here, takes us back to the definition of the assignment expression, or the walrus operator, that – it allows us to assign value to the variable, within an expression. So, again if you try to run the above program, you can simply see the correct output here.

So, we can make use of the walrus operator as and when required. It is a very useful feature at times. Remember that the walrus operator allows us to assign value to some variable, as a part of larger expression.