Python Walrus Operator

Python Walrus Operator – Examples

Walrus Operator := is an assignment operator. This feature is available starting from first Alpha version of Python 3.8. Let us see the following statement.

NAME := expr
Run this program ONLINE

Here, NAME is an identifier and expr is any valid Python expression other than an unparenthesized tuple.

What does this operator do? Well! This assignment not only assigns the value of expr to NAME, but the value of this named expression NAME := expr will be same as that of the incorporated expression expr.

Example 1: Basic usage of Walrus Operator

In this example, we provide basic usage of Walrus Operator and how does it effect the existing Python Code.

Evidently, Walrus Operator helps us to avoid writing the null check for the operator separately.

sample_data = [
    {"id": 1, "name": "Amol", "project": False},
    {"id": 2, "name": "Kiku", "project": False},
    {"id": 3, "name": None, "project": False},
    {"id": 4, "name": "Lini", "project": True},
    {"id": 4, "name": None, "project": True},
]

print("With Python 3.8 Walrus Operator\n------------------------") 
for entry in sample_data: 
    if name := entry.get("name"):
        print('Found Person:', name)

print("\nWithout Walrus Operator\n------------------------") 
for entry in sample_data:
    name = entry.get("name")
    if name:
        print('Found Person:', name)
Run this program ONLINE

Output

With Python 3.8 Walrus Operator
------------------------
Found Person: Amol
Found Person: Kiku
Found Person: Lini

Without Walrus Operator
------------------------
Found Person: Amol
Found Person: Kiku
Found Person: Lini
Run this program ONLINE