← Back

Walrus Operator

Python
Published:

Table of content

Walrus Operator

The walrus operator (:=) is a new syntax introduced in Python 3.8 that allows you to assign values to variables as part of an expression. This can be useful when you want to assign a value to a variable and use that value in the same expression.

For example, you can use the walrus operator to assign a value to a variable and use that variable in a conditional expression:

# Without walrus operator
x = 10
if x > 5:
    print(x)

# With walrus operator
if (x := 10) > 5:
    print(x)