Python Walrus Operator: Introduction, Example & Uses

Walrus Operator Python 3.8. Need, example and List comprehension. The walrus operator” is a new method, using which you can assign values to a variable

What is Python Walrus Operator

Walrus operator python was introduced in version 3.8 and is very useful to elegantly speed up code in specific scenarios. The := operator is called ‘walrus operator’ as it resembles the eyes and tusks of a walrus.

Pre-Requirements to use Python Walrus Operator

To use this new feature, you must have at least python 3.8 installed.
Below are instructions to install it in some popular operating systems –

Python Walrus Operator Usage

Suppose we have the following code –

a = [3, 5, 7]
i = 0
while(i < len(a)):
    print(i, len(a))
    i += 1

The above code is quite inefficient as it calculates the length of the list several times, at the start of every iteration of the loop. The most common way to speed up such code in long-running loops is –

a = [3, 5, 7]
i = 0
l = len(a)
while(i < l):
    print(i, l)
    i += 1

The above code is a great solution, it calculates the length beforehand in a separate variable, however, the walrus operator saves us a line of code. The below solution uses the walrus operator :=

a = [3, 5, 7]
i = 0
while(i < (l := len(a))):
    print(i, l)
    i += 1

The above code uses the := operator to assign a value to l. Now, what is the difference between = and :=. Both assign value to a variable right?, Let’s see the difference by experimenting.

Let’s try to print the value of expression a = 1,

print(a=1)

When I try to run the above code, I get an error, the one below is a brief of what I get –

Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'a' is an invalid keyword argument for print()

So, it seems, like the expression a = 1 is not printable. Probably, it does not return any printable value. It is a semantic error. Let’s try to print a := 1.

print(a:=1)

The above code prints 1. So, it seems the := operator when used to assign a value to an operator, returns the value assigned to it.

Note, := operator cannot be used as a statement. For example, we cannot use it like this

a := 1
print(a)

The above code produces, the error below –

Original exception was:
  File "", line 1
    a := 1
      ^
SyntaxError: invalid syntax

So, now we also know that we cannot use := for left most assignment. However, we can assign the value of 6 to both variables a and b, this way –

a = (b := 6)
print(a, b)

The above code prints “6 6“.

We can conclude, that the walrus operator needs to be used in an expression that must be a value to an operation.

Using Walrus Operator with If Statements

We can use := operator in if statements and avoid processing a value multiple times.

a = [1, 2, 3, 4, 5]
if l := len(a):
    print(l)

in the above code, the if statement checks whether the value returned from l := len(a) is a truthy value or not. if it is a truthy value, then the condition is satisfied and the statements in if-block are executed. Otherwise the else block statements are executed. Here, 5, is truthy value, so the length of a is printed.

All values are truthy, except for 0, False and empty list, string, tuple, dictionary, etc. You can get a complete list here.

Now, we might wonder the scope of the variable l. Can it be used in else block? We can check that

a = []
if l := len(a):
    print(l)
else:
    print("falsy value: ", l)

Output of the above code is “falsy value: 0“. The condition is not satisfied as the list is empty and the length of an empty list is zero, which is a falsy value. However, we were able to use the l variable in the else-block also.

Walrus Operator in List Comprehensions

The := operator is really handy in list comprehensions. To prove it’s worth, I will show you two examples. 1st example will not use it. But the 2nd one will. However, both examples aim to produce the output given below.

Example 1

print("\n".join(["*"*(6-i) + " "*i + "*"*(6-i) + " "*i + "*"*(6-i)   for i in range(7)]))

Example 2

print("\n".join(["*"*(a:=6-i) + " "*i + "*"*a + " "*i + "*"*a   for i in range(7)]))

In the above example, we can see that it looks that assigning the value of 6-i to a variable using the walrus operator is a more intuitive way.
Only when using for the first time, we assign the value to “a” while using it, at the same time. For subsequent requirements, we just use the variable.

I hope I was able to convince you that this new feature in python is great. Do convey your thoughts in the comments section below.

Leave a Comment