A new operator :
, pleasingly named the walrus operator—see the eyes and tusks— is known as an assignment expression.
The purpose of the walrus operator is to consolidate an assignment statement and a boolean expression when both assignment and expression would utilize a similar statement.
Let’s take a look at a simple use case and how we can implement the walrus operator to improve the efficiency of our code.
We’re going to check the length of a given list and print an error message that includes the length.
my_list = [1,2,3,4,5]
if len(my_list) > 3:
print(f"The list is too long with {len(my_list)} elements")
In case you’re unsure about the f
before the string in the print statement, that’s called a format-string literal, f-string for short.
Now, the walrus operator will eliminate calling the len()
function twice.
my_list = [1,2,3,4,5]
if (n := len(my_list)) > 3:
print(f"The list is too long with {n} elements")
The type of operator (assignment expression) should give you a hint about what is happening here. The inner-most statement is an assignment n = len(my_list)
then the value of n
is used in the outer expression.
Python isn’t known for requiring parenthesis very often, but in this case, they are critical for the statement to evaluate properly. To see the results of forgetting the parenthesis, let’s compare each by printing n
.
my_list = [1,2,3,4,5]
if (n := len(my_list)) > 3
print(n) # 5
if n := len(my_list) > 3:
print(n) # True
Notice that without the parenthesis, the evaluation of len(my_list) > 3
is assigned.
The walrus operator, allowing a compound assignment expression, opens up a host of new possibilities.
The introduction of this operator has also come with its fair share of criticism, but to me, it’s simply another tool in the kit that can be used when appropriate.
So, will you be using the walrus operator? If so, how will you be using it?
#python