Skip to content

Walrus

The walrus operator (:=), introduced in Python 3.8, is an assignment expression. It allows you to assign a value to a variable within an expression, such as an if statement or a list comprehension. This can make code more concise and efficient by avoiding redundant calculations.

# Without the walrus operator, you need two lines
n = len("Python")
if n > 5:
print(f"Length is {n}")
# With the walrus operator, you can combine them
if (n := len("Python")) > 5:
print(f"Length is {n}")
# Output:
# Length is 6