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 :

[pastacode lang=”python” manual=”a%20%3D%20%5B1%2C%202%2C%203%2C%204%5D%20%0Aif%20(n%20%3A%3D%20len(a))%20%3E%203%3A%20%0A%20%20%20%20print(f%22List%20is%20too%20long%20(%7Bn%7D%20elements%2C%20expected%20%3C%3D%203)%22)%20″ message=”” highlight=”” provider=”manual”/]

OUTPUT:

[pastacode lang=”python” manual=”List%20is%20too%20long%20(4%20elements%2C%20expected%20%3C%3D3)” message=”” highlight=”” provider=”manual”/]

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.

[pastacode lang=”python” manual=”sample_data%20%3D%20%5B%20%0A%20%20%20%20%7B%22userId%22%3A%201%2C%20%20%22name%22%3A%20%22rahul%22%2C%20%22completed%22%3A%20False%7D%2C%20%0A%20%20%20%20%7B%22userId%22%3A%201%2C%20%22name%22%3A%20%22rohit%22%2C%20%22completed%22%3A%20False%7D%2C%20%0A%20%20%20%20%7B%22userId%22%3A%201%2C%20%20%22name%22%3A%20%22ram%22%2C%20%22completed%22%3A%20False%7D%2C%20%0A%20%20%20%20%7B%22userId%22%3A%201%2C%20%20%22name%22%3A%20%22ravan%22%2C%20%22completed%22%3A%20True%7D%20%0A%5D%20%0A%20%20%0Aprint(%22With%20Python%203.8%20Walrus%20Operator%3A%22)%20%20%0Afor%20entry%20in%20sample_data%3A%20%20%0A%20%20%20%20if%20name%20%3A%3D%20entry.get(%22name%22)%3A%20%0A%20%20%20%20%20%20%20%20print(f’Found%20name%3A%20%22%7Bname%7D%22′)%20%0A%20%20%0Aprint(%22Without%20Walrus%20operator%3A%22)%20%0Afor%20entry%20in%20sample_data%3A%20%0A%20%20%20%20name%20%3D%20entry.get(%22name%22)%20%0A%20%20%20%20if%20name%3A%20%0A%20%20%20%20%20%20%20%20print(f’Found%20name%3A%20%22%7Bname%7D%22′)%20″ message=”” highlight=”” provider=”manual”/]

OUTPUT:

[pastacode lang=”python” manual=”With%20python%203.8%20walrus%20operators%20%3A%0AFound%20name%3A%20%E2%80%9Crahul%E2%80%9D%0AFound%20name%3A%20%E2%80%9Crohit%E2%80%9D%0AFound%20name%3A%20%E2%80%9Cram%E2%80%9D%0AFound%20name%3A%20%E2%80%9Cravan%E2%80%9D%0A%0AWithout%20Walrus%20operators%20%3A%0AFound%20name%3A%20%E2%80%9Crahul%E2%80%9D%0AFound%20name%3A%20%E2%80%9Crohit%E2%80%9D%0AFound%20name%3A%20%E2%80%9Cram%E2%80%9D%0AFound%20name%3A%20%E2%80%9Cravan%E2%80%9D%0A%E2%80%83%0A” message=”” highlight=”” provider=”manual”/]

 

Categorized in: