How to Use Walrus Operator in Python: Syntax and Examples
The walrus operator
:= in Python allows you to assign a value to a variable as part of an expression. It helps reduce code repetition by combining assignment and condition checks in one line.Syntax
The walrus operator uses the syntax variable := expression. It assigns the result of expression to variable and returns that value immediately.
This lets you use the assigned value right away in the same expression, such as inside an if or while condition.
python
if (n := len('hello')) > 3: print(f"Length is {n}")
Output
Length is 5
Example
This example shows how to read user input and check it in one line using the walrus operator. It assigns the input to user_input and tests if it is not empty.
python
while (user_input := input('Enter text (empty to quit): ')) != '': print(f'You entered: {user_input}') print('Done')
Output
Enter text (empty to quit): hello
You entered: hello
Enter text (empty to quit): world
You entered: world
Enter text (empty to quit):
Done
Common Pitfalls
One common mistake is using the walrus operator where a simple assignment would be clearer or where it reduces readability.
Another is forgetting that the walrus operator returns the assigned value, so it must be used in an expression context.
python
count = 0 # Wrong: using walrus outside expression context # count := 5 # SyntaxError # Right: use walrus inside an expression if (count := 5) > 3: print(f'Count is {count}')
Output
Count is 5
Quick Reference
Use the walrus operator to:
- Assign and use a value in the same expression
- Reduce repeated function calls or computations
- Make loops and conditions more concise
Remember it works only in Python 3.8 and later.
| Use Case | Example |
|---|---|
| Assign in condition | if (n := len(data)) > 0: |
| Assign in loop | while (line := file.readline()) != '': |
| Avoid repeated calls | if (result := expensive_func()) is not None: |
Key Takeaways
The walrus operator := assigns and returns a value in one expression.
Use it to simplify code by combining assignment and condition checks.
It works only in Python 3.8 and newer versions.
Avoid overusing it where it hurts readability.
It must be used inside an expression, not as a standalone statement.