How does Python Walrus Operator work?

Recently, it was only with the introduction of the Python 3.8 version that we became acquainted with the walrus operator. The walrus operator in Python introduced a new form of code writing and assigning values ​​to variables, thus facilitating some basic operations.

To put that operator in the context of the code, we need to understand what it actually does.

The Walrus operator assigns a value to a variable and therefore has an assignment operator function.

Walrus Operator Syntax

Its syntax is as follows. For example: ( x := 10 )

Parentheses are not a coincidence; it cannot be used as a stand-alone assignment operator. It must be part of a larger expression.

What would that mean in theory? Although the operator itself assigns a value to a variable, that variable should already be used somehow or should be “wrapped.”

Wrong syntax

x := “assign string”

The walrus operator doesn’t work this way, and SyntaxError: invalid syntax appears.

Right syntax

( x := “assign string” )

Python accepts this as an assignment of the string “assign string” on the variable x. Still, realistically it doesn’t make much sense to assign values ​​like this, so let’s find the proper use case.

Where to use the Walrus Operator?

Now that you understand how the walrus operator works, it would be interesting to find some use cases where the operator could be used.

Here are just a few of the use cases:

  • Walrus operator in loops
  • Walrus operator in if statement
  • Walrus operator in a list comprehension

Walrus operator in loops

There are 2 types of loops in Python, the for and while loops. The choice of the loop itself depends on the situation and the problem you want to solve.

How do the loops with the walrus operator work?

First, the for loop does not have any use case because the loop itself already does some sort of assignment of variables. For example, if we write for x in range (100), variable x will change through each iteration.

So here, the focus will be on the while loop, which has many use cases.

Example 1. – without walrus

sum = 0
number = int(input("Type 0 to quit "))
while number != 0:
    sum += number
    number = int(input("Type 0 to quit "))

print(sum)

# Output:
# Type 0 to quit 10
# Type 0 to quit 20
# Type 0 to quit 0
# 30

Example 1. – with walrus

sum = 0
while (number := int(input("Type 0 to quit "))) != 0:
    sum += int(number)

print(sum)

# Output:
# Type 0 to quit 10
# Type 0 to quit 20
# Type 0 to quit 0
# 30

Here, using the walrus operator, we assigned the int value of the input to the number and immediately checked if the number was different from 0. Pretty handy 🙂

As much as it turns out that we wrote a block of code in fewer lines, we can notice that the readability of the code has deteriorated a bit. Maybe it doesn’t seem like that in this simple example, but it will once you start writing large and complex operations.

The Python community is quite divided on this. And you can read more about it in summary.

Walrus operator in if statement

If statement is an unavoidable part of Python programming, we need to show how to use the walrus operator in it.

Example 1 – without walrus

strings = ["walrus", "operator", "python"]
strings_len = len(strings)

if strings_len > 0:
    print("strings list is not empty and it's length is", strings_len)

Example 1. – with walrus

strings = ["walrus", "operator", "python"]

if (strings_len := len(strings)) > 0:
    print("strings list is not empty and it's length is", strings_len)

In this example, we assign a numeric value to the variable inside the if statement. If the list is not empty, we print its length, ie, the number of members.

Walrus operator in a list comprehension

List comprehension is a tool that creates lists in Python, it is quite an elegant way to create a list, mainly from an existing list.

How does the walrus operator play this role? So with it, we can check and optimize part of the code and avoid calling the function more times than is actually necessary.

So let’s look at the first example.

Example 1. – without walrus

f = lambda x: len(x)**3.8
strings = ["walrus", "operator", "in", "python"]

strings_data = [f(string) for string in strings if (f(string) > 3)]
print(strings_len)

As we can see here, the lambda function is called first when checking or comparing with the number 3, then the function is called again when adding the value to the list. If it were a large list and a time-consuming function, there would be optimization problems, and this can be avoided.

Let’s look at the following example.

Example 1. – with walrus

f = lambda x: len(x)**3.8

strings = ["walrus", "operator", "in", "python"]

strings_len = [x for string in strings if ((x := f(string)) > 3)]
print(strings_len)

In this example, the lambda function is called once. The variable x is assigned its value, which then does not need to be recalculated. If the condition is met, it is added to the list. We see that we have saved on one function call.

Summary

The Python community is very divided when it comes to the Walrus operator. So why are people skeptical?

The walrus operator itself may corrupt the code’s readability, which conflicts with Zen of Python. Whether the walrus operator will come to life and gain even greater popularity remains to be seen.

This fairly new feature has yet to be explored as part of the Python community. Time will tell!