Open In App

Walrus Operator in Python 3.8

Improve
Improve
Like Article
Like
Save
Share
Report

The Walrus Operator is a new addition to Python 3.8 and higher. In this article, we’re going to discuss the Walrus operator and explain it with an example.

Introduction

Walrus Operator allows you to assign a value to a variable within an expression. This can be useful when you need to use a value multiple times in a loop, but don’t want to repeat the calculation.

The Walrus Operator is represented by the := syntax and can be used in a variety of contexts including while loops and if statements. The Assignment expressions allow a value to be assigned to a variable, even a variable that doesn’t exist yet, in the context of expression rather than as a stand-alone statement.

Code :

Python3




numbers = [1, 2, 3, 4, 5]
 
while (n := len(numbers)) > 0:
    print(numbers.pop())


Output :

Screenshot-2023-09-20-at-23927-PM

In this example, the length of the numbers list is assigned to the variable n using the Walrus Operator. The value of n is then used in the condition of the while loop, so that the loop will continue to execute until the numbers list is empty.

Example –

Let’s try to understand Assignment Expressions more clearly with the help of an example using both Python 3.7 and Python 3.8. Here we have a list of dictionaries called “sample_data”, which contains the userId, name and a boolean called completed.

Python3




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:

Here is another example:

Python3




## The below example is without Walrus Operator
foods = list()
while True:
  food = input("What food do you like?: ")
  if food == "quit":
    break
    foods.append(food)
 
# Below Approach uses Walrus Operator
foods1 = list()
while (food := input("What food do you like:=  ")) != "quit":
    foods.append(food)


Output:

Screenshot-2023-09-20-at-25140-PM

Note: This example, the user input is assigned to the variable name using the Walrus Operator. The value of name is then used in the if statement to determine whether it is in the names list. If it is, the corresponding message is printed, otherwise, a different message is printed.



Last Updated : 24 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads