Colon Equals Operator aka Walrus Operator in Python

Colon Equals Operator aka Walrus Operator in Python

ยท

1 min read

Python 3.8 introduced the 'colon equals' operator := which is the same as the equals operator = in any of the programming languages.

Both are used for assignments of any value.

'=' operator

operator = "equals operator" # assigning 'operator' variable
print(operator)
# Output-> equals operator

:= operator

print(operator := "Walrus operator") # combining assignment and
                                     # printing operations
# Output-> Walrus operator

This operator is also known as Walrus Operator. It is used for assigning and returning a value within the same expression.

array = [1,2,3,4,5]
num = 3
if array.index(num) == num-1: # O(n) time complexity for index()
    print(array.index(num))   # O(n)
else:
    ...
# Output-> 2

In the above example, we are calling the index() method twice. := operator helps us avoid calling the method twice. Hence, improving the complexity and removing redundancy.

array = [1,2,3,4,5]
num = 3
if (index := array.index(num)) == num-1:
    print(index)
else:
    ...
#Output-> 2

The index of num variable (which is 2) is assigned to index variable first and then evaluates the rest expression.

Thanks for reading!

ย