Ask Your Question

Revision history [back]

The walrus operator or ":=" is a new assignment expression that was introduced in Python 3.8. It allows the assignment of values to a variable as part of an expression.

For example, instead of writing:

x = 5
if len(some_list) > 10:
    print(x)

We can now write:

if (x:=5) and len(some_list) > 10:
    print(x)

The walrus operator is useful in situations where we want to both assign a value to a variable and use the value in the same expression.

The main motivation behind adding this syntax was to make code more concise and readable. It also helps reduce code duplication by allowing us to assign values to variables that are used only once in an expression.