Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
python 3
walrus
communitycreator

What is the walrus operator in Python?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)

RELATED TAGS

python
python 3
walrus
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring