#Day10 - Walrus Operator in Python

#Day10 - Walrus Operator in Python

In today's article, we will talk about the Walrus Operator := in Python. The walrus operator is an assignment operator which was introduced in Python 3.8. But it is not just an assignment operator, it also returns the value after the assignment.

This is the general syntax of the walrus operator

(var := expression/ function)

Although the parenthesis is not necessary, it is a good practice

So what does the Walrus operator do?

  • The value of the expression is assigned to the variable var
  • After assignment, the value is also returned.

Before Python 3.8, if you wanted to assign the value returned by an expression/function to a variable and print the value, below is how you would do it

var = expression/function
print(var)

But using the walrus operator, this can be done in a single line

print(var := expression/function)

Let's compare some code snippets with and without the walrus operator

Python 3.7

def func(x):
    return x+1

var = 0
var = func(var)
print(var)

Python 3.8

def func(x):
    return x+1

var = 0
print( var := func(var) )

The value returned by the function func is first assigned to the variable var. After the assignment, the value is returned and the print statement displays it on the command line.

If statements

Python 3.7

lst = [1,2,3]
n = len(lst)
if n < 10:
    print("It is a small list")
print(n)

Python 3.8

lst = [1,2,3]
if (n:= len(lst)) < 10:
    print("It is a small list")
print(n)

while loop

Python 3.7

n = 0
while(n < 10):
    print(n)
    n +=1

Python 3.8

n = 0
while(n := n +1) < 10:
    print(n)

Lists

Python 3.7

def func(x):
    return x + 1

y = func(2)
lst = [y , y*y , y*y*y]
print(lst)

Python 3.8

def func(x):
    return x + 1

lst = [y:=func(2),y*y,y*y*y]
print(lst)

List Comprehension

Python 3.7

def computationally_expensive_function(x):
    '''
    Imagine this is some computatationally expensive function
    '''
    return 2

nums = [1,2,3]

lst = [computationally_expensive_function(num) for num in nums if computationally_expensive_function(num) > 0]
print(lst)

Python 3.8

def computationally_expensive_function(x):
    '''
    Imagine this is some computatationally expensive function
    '''
    return 2

nums = [1,2,3]

lst = [var for num in nums if (var := computationally_expensive_function(num))> 0]
print(lst)

Instead of calling the computation expensive function twice, we only call it once when using the walrus operator.