python tip

The Walrus(:=) Operator

This is one of the latest additions to Python. The walrus operator was added to Python in version 3.8. It is basically an assignment expression that allows assignment directly in the expression. Usual way:

a = [1,2,3]
b=len(a)
if b > 2:
      print(b)

In the above-mentioned example, we declared a list. Then we declared a variable ‘b’ to assign the value of the length of the list. But by using the walrus operator:

a = [1,2,3]
if (b := len(a) > 2):
      print(b)

Here, we declared and assigned the value at the same time. This method helps to decrease the lines of code too.