What is the purpose of 'walrus operator' (:=) introduced in Python 3.8?

Understanding the Walrus Operator in Python 3.8

Python 3.8 introduced a new operator known as the 'walrus operator' or ':='. It's called the assignment expression, it is designed to handle a common case where a value needs to be assigned to a variable and then the variable is immediately used in an enclosing context.

The main purpose of the walrus operator is to assign values to variables as part of an expression. This is different from the = operator that assigns a value to a variable. The := operator checks an expression’s value and assigns it to a variable in a single step.

Let's look at a practical example to understand its functionality:

Suppose you want to take a list of numbers and get the first number that is larger than 10.

numbers = [7, 11, 8, 5, 3, 12, 2, 6]

for num in numbers:
    if num > 10:
        first_greater = num
        break

Without the walrus operator, you would have to use an if statement like the one above. But with the walrus operator, you can simplify the code:

numbers = [7, 11, 8, 5, 3, 12, 2, 6]

if (n := next((num for num in numbers if num > 10), None)) is not None:
    print("The first number greater than 10 is:", n)

In the above code, n := next((num for num in numbers if num > 10), None) will assign the first number from the list that is greater than 10 to n, and then the if statement can immediately check if n is not None.

Python's addition of the 'walrus operator' demonstrates the ongoing evolution and refinement in the programming language. It is important to note that, while this operator can shorten certain types of code, it can also make the code more complex or harder to read if not used wisely. For this reason, it is advisable to use this operator sparingly and only when it improves the overall readability of the code.

Do you find this helpful?