Walrus Operator in Python

The walrus operator (:=) in Python (introduced in Python 3.8) is called the assignment expression operator.

It allows us to assign a value to a variable as part of an expression instead of doing it separately.

Basic Idea Normally, you might do this:

Syntax

n = len([1, 2, 3, 4])
if n > 2:
    print(f"List is too long ({n} elements)")

With the walrus operator:

Syntax

if (n := len([1, 2, 3, 4])) > 2:
    print(f"List is too long ({n} elements)")

Here:
• (n := len(...)) assigns the value to n and returns it for comparison.