Walrus Operator in Python

In the following tutorial, we will learn about the Walrus Operator in Python.

What is the Walrus Operator?

With the latest development in Python 3.8, we have observed the addition of a new operator known as the “walrus” operator. This operator is an assignment expression in Python 3.8 and the syntax for the following assignment expression is “:=”.

Why is it called the Walrus Operator?

This expression is known as the “walrus” operator since it looks similar to “the eyes and tusks of a walrus”. (According to official documentation). Python 3.8 is still under development.

How to Implement the Walrus Operator?

The python documentation mentions the syntax as “:=” and states that it performs the assignment operation of the values to the variables.

Normally we would first have an assignment statement and then another statement to return the assigned value to the variable. However, using the walrus operator you can have a combined statement to perform those tasks. When you want to assign value to a variable and return the value you would usually do it in the following way:

x=True
print(x)

Output:

True

However, using the walrus operator we can write the code in the following way:

print(x:=True)

From the code snippet above we can see that the value of “x” is being assigned to True and being returned using the same statement.

Output:

True

Program to Demonstrate the Walrus Operator

student_names = [ 
    {"roll": 1,  "stu_name": "Michael"}, 
    {"roll": 2, "stu_name": "Dwight"}, 
    {"roll": 3,  "stu_name": "Jim"} ]

for x in student_names:
    if stu_names:=x.get("stu_name")
        print('The name of the student is:',stu_names) 

Output:

The name of the student is: Michael
The name of the student is: Dwight
The name of the student is: Jim

Also read: About Inplace operator in Python

Leave a Reply

Your email address will not be published. Required fields are marked *