What is the walrus operator in Python?

What is the walrus operator in Python?

The walrus operator allows us to assign a value to a variable and return that value, all in the same expression. Hence, it reduces two steps to a single step. This feature was introduced in Python 3.8.

Example

Without walrus operator:

new_var = "Hello"
print(new_var)

With walrus operator:

print(new_var:="Hello")

Let’s look at different examples of walrus operators.

How to use the walrus operator in an if condition

The following is an example of how we can use the walrus operator in an if condition.

Print all of the words with lengths less than 4.

all_words = ['hello', 'hi', 'welcome', 'world', 'oh', 'common']
for one_word in all_words:
if ((word_len := len(one_word)) < 4):
print(f'The word "{one_word}" has {word_len} characters')

How to use the walrus operator in dictionary comprehension

The following is an example of the use of walrus operator in dictionary comprehension.

Let’s say we have a list of numbers. Return a dictionary with key as number and value as the square root of a number whose square root is less than 10.

import math
sqrt = lambda x: math.sqrt(x)
num_list = [1,25, 100, 800, 1000, 2323, 45432]
nums_sqrt = {num:num_sqrt for num in num_list if (num_sqrt:=sqrt(num)) < 10}
print(nums_sqrt)

Free Resources