Last modified: Apr 04, 2026 By Alexander Williams
Python Walrus Operator Guide: := Syntax
The walrus operator is a new syntax in Python. It was introduced in Python 3.8. Its official name is the assignment expression.
This operator allows you to assign a value to a variable. The assignment happens inside an expression. This can make your code more concise.
The symbol for the operator is :=. It looks like the eyes and tusks of a walrus. That is how it got its nickname.
What is the Walrus Operator?
Before Python 3.8, assignment was a statement. You could not use it inside other expressions. The walrus operator changes this rule.
It lets you assign and return a value in one step. This is useful in many common coding patterns. It reduces repetition and can improve readability.
The basic syntax is variable_name := expression. The expression is evaluated. The result is assigned to the variable. The result is also returned for use in the larger expression.
Basic Syntax and First Example
Let's look at a simple example. Imagine you are reading user input. You want to check if the input is not empty.
Here is the traditional way without the walrus operator.
# Traditional method
user_input = input("Enter text: ")
while user_input != "":
print(f"You entered: {user_input}")
user_input = input("Enter text: ")
Notice the repetition. The line user_input = input("Enter text: ") appears twice. This is not ideal.
Now, see the same logic using the walrus operator.
# Using the walrus operator
while (user_input := input("Enter text: ")) != "":
print(f"You entered: {user_input}")
The code is shorter and cleaner. The assignment happens inside the while condition. The value is checked against "" immediately.
The variable user_input is available inside the loop body. This is a powerful and common use case.
Common Use Cases and Examples
The walrus operator shines in loops and comprehensions. It helps avoid recalculating expensive expressions.
1. In While Loops
We saw the input example. This pattern applies to reading from files or sockets. You read data and check its validity in one line.
# Reading lines from a file until a sentinel value
with open('data.txt') as file:
while (line := file.readline().strip()) != "END":
print(f"Processing: {line}")
2. In List Comprehensions
You can use it to filter and transform data efficiently. Imagine processing items but only keeping results that pass a test.
# Process numbers, but only keep results if processing is successful
data = ["10", "twenty", "30", "forty"]
processed = [num for val in data if (num := safe_convert(val)) is not None]
# Let's define a simple safe_convert function for this example
def safe_convert(s):
try:
return int(s)
except ValueError:
return None
print(processed)
[10, 30]
The safe_convert function is called once per item. Its result is assigned to num. The result is then used in the filter and the output expression.
3. Avoiding Repeated Function Calls
Sometimes you need to call a function, check its result, and use it. Doing this twice is inefficient.
# Inefficient way
result = expensive_calculation(data)
if result > threshold:
do_something(result)
# Efficient way with walrus
if (result := expensive_calculation(data)) > threshold:
do_something(result)
This ensures expensive_calculation is called only once. This is a key benefit for performance.
Important Rules and Pitfalls
The walrus operator is powerful but has rules. Understanding them prevents bugs.
Parentheses are often required. The operator has low precedence. You must use parentheses to group the assignment expression correctly. This is the most common source of syntax errors.
# This will cause a SyntaxError
if n := 5 > 4: # Wrong! It's interpreted as n := (5 > 4)
print(n)
# This is correct
if (n := 5) > 4:
print(n)
True
5
It is an expression, not a statement. You can use it anywhere Python expects an expression. This includes function arguments, lambda functions, and dictionary values.
Do not overuse it. The goal is clarity. If a line becomes too complex, break it up. Traditional assignment might be clearer.
Comparison with Traditional Assignment
The standard assignment operator is =. It is a statement. It cannot be used inside other expressions.
The walrus operator := is an expression. It can be embedded. This is the core difference.
Use = for simple, standalone assignments. Use := when you need to assign and use a value immediately in a larger context.
Conclusion
The Python walrus operator is a valuable tool. It helps write more concise and efficient code.
Its main use is in loops and comprehensions. It eliminates repetition of function calls or calculations.
Remember to use parentheses. Do not sacrifice readability for cleverness. Start using it in your while loops and list comprehensions first.
With practice, you will find it makes your Python code cleaner. It is a great addition to the language for intermediate developers.