The Walrus Operator In Python

The walrus operator (:=) was introduced in Python 3.8 and is used for assignment expressions. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus. It assigns a value to a variable as part of an expression, allowing you to capture the result of an expression while also using it in the context of a conditional statement or loop. Here are some examples of its usage:

Using the walrus operator with an if statement

This is a very simple snippet of code, where we check the length of a list and if it is under 10 we print a statement.

Without Walrus operator

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

if len(numbers) < 10:
    print(f'List length is {len(numbers)}, should be 10')


With Walrus operator

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

if (x := len(numbers)) < 10:
    print(f'List length is {x}, should be 10')

As you can see from the example above, in our if statement we are assigning the value of the length of the numbers list (9) to a variable x. We can then reference this value in our if statement without having to use len(numbers) again.

Using the walrus operator with a while loop

In this example, we are asking the user to add items to their shopping list or to type quit to exit the program.

Without Walrus operator

shopping_list = []
while True:
    item_input = input('Add an item or type quit to exit ')
    if item_input == 'quit':
        break
    shopping_list.append(item_input)
    print(shopping_list)

With Walrus operator

shopping_list = []
while (item_input := input('Add an item or type quit to exit ')) != 'quit':
    shopping_list.append(item_input)
    print(shopping_list)

With the help of the walrus operator, we can easily assign the value from the input to the item_input variable while we are comparing the statement.

Using list comprehensions

Without Walrus operator In this approach, we generate random numbers and filter them based on a condition (num >= 50) using a for loop and explicit list appending

import random

def get_random_number():
    '''
    Generates random numbers between 1 and 100
    '''
    return random.randrange(1, 100)

rand_nums_above_fifty = []

# Perform the loop 20 times
for _ in range(20):
    num = get_random_number() 
    if num >= 50:
        rand_nums_above_fifty.append(num) 

print(rand_nums_above_fifty)

With Walrus operator In this approach, we use a list comprehension with the walrus operator (:=) to generate random numbers and filter them based on a condition (num >= 50).

import random
def get_random_number():
    '''
    Generates a random number between 1, 100
    '''
    return random.randrange(1, 100)


rand_nums_above_fifty = [num for _ in range(
    20) if (num := get_random_number()) >= 50]
print(rand_nums_above_fifty)

In conclusion, the walrus operator (:=) is a powerful addition to Python's syntax, offering a more concise and readable way to handle assignment expressions within conditional statements, loops, and list comprehensions. Its ability to combine assignment with expression evaluation simplifies code and improves its clarity, especially in scenarios where reducing redundancy is crucial.

PythonWalrus Operator
Avatar for Dayana

Written by Dayana

Currently studying Full stack software development. I love coding, cars and music :)

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.