Top Rated Plus on Upwork with a 100% Job Success ScoreView on Upwork
retzdev logo
logo
tech

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.

Jarrett Retz

Jarrett Retz is a freelance web application developer and blogger based out of Spokane, WA.

jarrett@retz.dev

Subscribe to get instant updates

Contact

jarrett@retz.dev

Legal

Any code contained in the articles on this site is released under the MIT license. Copyright 2024. Jarrett Retz Tech Services L.L.C. All Rights Reserved.