Python & the Walrus Operator

By Jarrett Retz -October 18th, 2020

What is the Walrus Operator?

If you are looping over an array it's possible to get the current value of the iteration to execute expressions on.

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for num in a:
	print(num)
	
	
# Output

0
1
2
3
4
5
6
7
8
9
10

However, in other statements or larger expressions, a value needs to be assigned in the predicate and then used again in the following code block. We can demonstrate this with an if statement.

This is similar to the example used in Python's documentation.‚Äč

if (len(a)) > 10:
	print(f'{len(a)} is too long, expected <= 10')
	
	
# Output
# 11 is too long, expected <= 10

In the above expression, we call len twice. We can avoid calling len twice by using the walrus operator.

if (n := len(a)) > 10:
	print(f'{n} is too long, expected <= 10')
	

# Output
# 11 is too long, expected <= 10

This can be useful in:

  • while loops
  • if blocks
  • list comprehensions

In the next section, we'll take a quick look at using the new operator in list comprehensions.

Usage in List Comprehensions

Another motivating use case arises in list comprehensions where a value computed in a filtering condition is also needed in the expression body...

This example is a bit contrived, and not very realistic, but I'm using it anyway because it's easy.

names = ['Albert', 'Mary', 'Stacy', 'john']

needs_to_capitalize = [names[i].capitalize() for i in range(len(names))
 if names[i].islower()]

print(needs_to_capitalize)

# Output
# ['John']

The above expression can use the walrus operator in the following way.

names = ['Albert', 'Mary', 'Stacy', 'john']

needs_to_capitalize = [n.capitalize() for i in range(len(names))
 if (n := names[i]).islower()]

print(needs_to_capitalize)

List comprehensions can be difficult to read in their own right. However, the walrus operator can help clean up the mess.


Have a thought about the article?

Send JRTS a message!

We'll never share your email with anyone else.

Contact