Python 3.8 remains in development. But many alpha versions are released. one among the newest features in Python 3.8 is that the Walrus Operator. during this article, we’re getting to discuss the Walrus operator and explain it with an example.

Introduction

Walrus-operator is another name for assignment expressions. consistent with the official documentation, it’s how to assign to variables within an expression using the notation NAME := expr. The Assignment expressions allow a worth to be assigned to a variable, even a variable that doesn’t exist yet, within the context of expression instead of as a stand-alone statement.

Code :

a = [1, 2, 3, 4] 
if (n := len(a)) > 3:
print(f"List is too long ({n} elements, expected <= 3)")

OUTPUT:

List is too long (4 elements, expected <=3)

Example –

Let’s plan to understand Assignment Expressions more clearly with the help of an example using both Python 3.7 and Python 3.8. Here we’ve a listing of dictionaries is named “sample_data”, which contains the user Id, name and a Boolean called is completed.

sample_data = [ 
{"userId": 1, "name": "rahul", "completed": False},
{"userId": 1, "name": "rohit", "completed": False},
{"userId": 1, "name": "ram", "completed": False},
{"userId": 1, "name": "ravan", "completed": True}
]

print("With Python 3.8 Walrus Operator:")
for entry in sample_data:
if name := entry.get("name"):
print(f'Found name: "{name}"')

print("Without Walrus operator:")
for entry in sample_data:
name = entry.get("name")
if name:
print(f'Found name: "{name}"')

OUTPUT:

With python 3.8 walrus operators :
Found name: “rahul”
Found name: “rohit”
Found name: “ram”
Found name: “ravan”

Without Walrus operators :
Found name: “rahul”
Found name: “rohit”
Found name: “ram”
Found name: “ravan”

 

Categorized in: