Python

Python walrus operator (Assignment Expression)

Python is rich in operators of various kinds. All the different kinds of operators that Python has perform unique tasks. Python is still in its development phase, where the community developers keep trying to add new features to make programming easier & efficient.

Python’s version 3.8 brings the walrus operator (:=) that provides new syntax to enable programmers to assign variables in the middle of expressions. This article will give you an in-depth understanding of the Python walrus operator and how to use it.

 

 

What is the walrus operator in Python?

Walrus operator is a special type of operator that got introduced with Python 3.8. This operator provides a way of assigning variables within an expression with the help of the notation:

NAME := expr.

The operator is named so because its colon looks like the eyes and = like the tusks of a walrus. Programmers can also call it assignment expression or named expression.

But the advent of the walrus operator is controversial and many developers and programmers criticized it because it failed to satisfy some of the guiding principles the creator Guido van Rossum created for Python (mentioned in Zen of Python).

It also became the reason why Guido van Rossum stepped down from his role as “Benevolent Dictator For Life (BDFL)”.
According to the PEP 572‘s title, this operator is called the “assignment expression.” Again, according to the CPython implementation references, it is called “named expressions.”

Here is a code snippet showing how the walrus operator helps initialize the variable l within the expression by storing the length of the list li through the len() function.

li = [2, 4, 6, 8, 10]
if (l := len(li)) > 3:
    print(f"The list object is too long (containing {l} elements. Expected <= 3)")
else:
    print("the list size is perfect as expected")

Output

This output shows waht is walrus operator in Python

 

How to use the walrus operator?

There are different situations where the walrus operator can best fit with its role. We can use it with normal expressions, within the if statement, with a loop, etc. But its initialization always has to be there within an expression.
Example:

print(is_there := True)

Output

This output shows how to use walrus operator in Python
Another example:

numb = [1,2,3,4,5,6,7,8]
for no in numb:
    if ((n := max(numb)) > 3):
        print(f'The list {numb} has {n} digits')
        break
    else:
        print("The list is empty")

Output

This output shows another example of how to use walrus operator in Python

 

Variable assignment

Python allows programmers to use the walrus operator to assign variables within an expression. We can call such variable as the walrus variable.

A traditional assignment never returns any value while an assignment expression driven by the walrus operator will return a value.

z= (walrus:=10)
print(z)

Output

This output shows Python walrus operator variable assignment
Or

(z:=(3+5))
print("The variable z after assigning within an expression stores: ", z)

Output

This output shows another example of Python walrus operator variable assignment

 

Walrus operator within for loop

Programmers can use the walrus operator within a “for” loop to accommodate any assignment within it. Here is a code snippet showing how to do it.

numb = [1,2,3,4,5,6,7,8]
for no in numb:
    if ((n := len(numb)) > 3):
        print(f'The list {numb} has {n} digits')
        break
    else:
    	print("The list is empty")

Output

This output shows walrus operator for loop in Python

 

Walrus operator with a while loop

Programmers can also use the walrus operator while working with a while loop. Here is a code snippet showing how the general way to use a while loop.

inputs = list()
print("Want to write unlimited? ")
cur = input("Write >>> ")
while cur != "quit": #this loop keeps on going until we write the ‘quit’
    inputs.append(cur)
    cur = input("Write >>> ")

Output

This output shows walrus operator while loop in Python

We can write the same above code using the walrus operator to reduce a few lines.

inp = list()
while (cur := input("Write >>> ")) != "quit":
    inp.append(cur)

Output

This output shows another example walrus operator while loop in Python

 

List comprehension

List comprehensions are a smarter way of coding where Python offers programmers to write a shorter syntax while creating a new list based on the values of an existing list.

Programmers can use the Walrus operator within a list comprehension so that the function does not require multiple calling.

That makes the entire operation lightweight and efficient. Here is a code snippet showing its use.

f = lambda s: s**2
dat = [1, 2, 3, 4, 5, 6]
filtered_power_dat = [g for s in dat if (g := f(s)) > 8]
print(filtered_power_dat)

Output

This output shows walrus operator in list comprehension in Python

 

Dictionary comprehension

Like list comprehension, Python enables programmers to write dictionary-based comprehensions also.

A dictionary comprehension takes the key and the value for (key, value) in an iterable fashion.

Here, in a dictionary comprehension can use the walrus operator. Here is a code snippet to show you how we can use it.

dicto = {"A": [40, 62, 65], "B": [35, 62, 70, 82], "C": [28, 45, 80], "D":[91, 77]}
q = {g: mean for g in dicto if (mean := (sum(dicto[g]) // len(dicto[g]))) > 60}
print(q)

Output

This output shows walrus operator dictionary comprehension in Python

 

Walrus operator with if statement

Programmers can use the walrus operator with different if statements such as if, if-else, elif, etc. also. We can use it to initialize the conditional expression’s value for the if.

Here is a code snippet to show you how we can use it.

my_li = [8, 7, 6]
cnt = len(my_li)
if cnt > 4:
   print(f"Error, {cnt} is too many items")
# when using the walrus operator...
elif (count := len(my_li)) < 4:
   print(f"Good, {cnt} is the number of times and the number of items")
else:
   print(f"No way")

Output

This output shows walrus operator with if statement in Python

 

Walrus operator with regex

Regular expressions in Python are special character sequences that help in searching a particular pattern, string, sub string, or set of strings.

It can identify the presence or absence of a string or substring by comparing it with a particular pattern. We can also a regex pattern into multiple sub-patterns.

Python programmers can use the walrus operator with a regex to initialize values within the expression as a part of the pattern. Here is a code snippet to show you how we can use it.

import re
def get_number(n):
    if g := re.match(f'^.+ (\d\d)-(\d\d)-(\d\d\d\d)$', n):
        print( g.group(3) + g.group(2) + g.group(1))
get_number('karlos 28-08-2022')

Output

This output shows walrus operator regex in Python

 

Python walrus operator not working (invalid syntax or unsupported version)

As we all know that expressions & assignment statements are not the same in Python, this is the primary reason why an invalid syntax error pops up, and the entire program stops working.

The main reason is such assignments always occur within an expression and not in the form of a statement.

walrusop := True
print(walrusop)

Output

This output shows walrus operator not working in Python
To resolve this error, programmers should convert the statement to an expression using a pair of parenthesis. It is because the nature of walrus operators says that it will initialize value(s) always within an expression.

(walrusop := True)
print(walrusop)

Output

This output shows resolving errors of walrus operator (invalid syntax) in Python

 

Conclusion

Operators are one of the primary building blocks in Python. Walrus is also an operator that got introduced with Python 3.8.

It provides a way of assigning variables with an expression, i.e., within a pair of parenthesis.

Assigning any value within an expression, conditional expression in any loop, decision making statement, lambda function, regular expression, or any other sub-expression can be accomplished using the walrus operator.

It acts as a handy way of initializing values to any variable on the go.

Leave a Reply

Your email address will not be published. Required fields are marked *