Skip to main content

The Walrus Operator

Introduced in Python 3.8, the walrus operator (:=) allows us to assign a value to a variable inside an expression. This differs from a standard statement (x = 5), which performs an action but doesn't return a value. The walrus operator assigns a value and returns it at the same time, behaving like an expression (3 + 3).

Reducing Redundancy​

The walrus operator is ideal for reducing redundant function calls or simplifying conditions when we need to calculate a value and then immediately check it in an if statement.

# Standard way: two lines
remainder = 13 % 5
if remainder:
print(f"Has remainder: {remainder}")

# Pythonic way: one line
if (rem := 13 % 5):
print(f"Has remainder: {rem}")
Has remainder: 3
Has remainder: 3

In more complex scenarios, like fetching an environment variable or reading from a file, it prevents we from having to call an expensive function twice.

Simplifying While Loops​

The walrus operator is perfect for "loop until empty" patterns, keeping the assignment and the check in one place.

# This loop continues as long as the user types something
while (user_input := input("Enter something (empty to stop): ").strip()):
print(f"We typed: {user_input}")
Enter something (empty to stop): hello
We typed: hello
Enter something (empty to stop):
Use with Care

Don't use the walrus operator if it makes the code harder to read. If a line becomes too complex, a standard assignment is usually better.