Definition of the walrus operator in Python
The walrus operator, introduced with Python 3.8 (PEP 572), is an assignment expression operator denoted :=. Its official name is assignment expression, but the community nicknamed it "walrus" because the symbol := resembles the eyes and tusks of a walrus turned on its side.
Unlike the classic assignment operator =, the walrus operator allows you to assign a value to a variable while using it in an expression. This means you can perform an assignment and immediately use the result in the same line of code, making certain constructs much more concise.
If you want to master this type of advanced feature and all the subtleties of the language, our comprehensive Python course will guide you step by step through your learning journey.
The walrus operator := is a powerful tool for reducing redundancy in your code, but it should be used with discernment so as not to harm readability.
Syntax of the walrus operator
The syntax of the walrus operator is simple:
(variable := expression)The expression is evaluated, its value is assigned to variable, and that same value is returned for use in the surrounding context. Parentheses are often necessary to avoid syntactic ambiguities.
Let's look at a minimal example to clearly understand the difference with a classic assignment:
# Classic assignment (statement)
x = 10
print(x) # 10
# With the walrus operator (expression)
print(y := 20) # 20 — y is assigned AND displayed at the same timeIn the first case, the assignment and the display are two separate statements. In the second, the walrus operator allows you to combine both into a single line using the print function.
Difference between = and :=
It is essential to clearly understand what distinguishes these two operators:
| Characteristic | Classic assignment = | Walrus operator := |
|---|---|---|
| Type | Statement | Expression |
| Usable in an expression | No | Yes |
| Usage context | Anywhere as a statement | In conditions, loops, comprehensions |
| Minimum Python version | All | 3.8+ |
| Parentheses required | No | Often yes |
The key point is that = is a statement: it cannot be placed inside an expression such as a function call or an if condition. The walrus operator :=, on the other hand, is an expression that returns a value, making it usable in these contexts.
Practical examples of the walrus operator
Usage in a while loop
One of the most common use cases of the walrus operator is reading data in a while loop. Without walrus, you often need to duplicate the read call:
# Without the walrus operator
line = input("Enter text (or 'quit' to stop): ")
while line != "quit":
print(f"You wrote: {line}")
line = input("Enter text (or 'quit' to stop): ")Notice that the call to input() is duplicated. With the walrus operator, we can simplify this code:
# With the walrus operator
while (line := input("Enter text (or 'quit' to stop): ")) != "quit":
print(f"You wrote: {line}")The code is more concise and eliminates the duplication. The variable line receives the value of input() and is immediately compared to "quit" in the same expression. Note the use of an f-string for formatted output.
Usage in an if condition
The walrus operator is also very useful in if conditions to avoid computing the same thing twice:
# Without the walrus operator
results = search_user("Alice")
if results:
print(f"{len(results)} result(s) found")
process(results)
# With the walrus operator
if (results := search_user("Alice")):
print(f"{len(results)} result(s) found")
process(results)Here, the call to search_user() is performed only once, and the result is both assigned to results and evaluated as a condition. The len function then allows us to know the number of results.
Usage with regular expressions
Another classic use case is processing regular expression (regex) matches:
import re
text = "My email is contact@believemy.com"
# Without the walrus operator
match = re.search(r'[\w.+-]+@[\w-]+\.[\w.-]+', text)
if match:
print(f"Email found: {match.group()}")
# With the walrus operator
if (match := re.search(r'[\w.+-]+@[\w-]+\.[\w.-]+', text)):
print(f"Email found: {match.group()}")This pattern is extremely common in professional Python code, especially when you chain multiple match attempts with elif.
Usage in list comprehensions
The walrus operator can avoid redundant calculations in list comprehensions:
# Without the walrus operator — expensive_calc() is called twice per element
results = [
expensive_calc(x)
for x in data
if expensive_calc(x) > threshold
]
# With the walrus operator — expensive_calc() is called only once
results = [
y
for x in data
if (y := expensive_calc(x)) > threshold
]In the second example, the value of expensive_calc(x) is assigned to y in the if filter, then reused in the comprehension expression. This can represent a significant performance gain when the function is computationally expensive.
Usage with file reading
Reading files in chunks is an elegant use case:
# Reading a file in 1024-byte chunks
with open("large_file.txt", "r") as f:
while (chunk := f.read(1024)):
process_chunk(chunk)Without the walrus operator, you would need a more verbose structure with a pre-read and a re-read at each loop iteration.
Usage in a dictionary
You can also use the walrus to build data structures like dict conditionally:
raw_data = ["Alice:85", "Bob:92", "Charlie:78", "Diana:95"]
# Filter and transform in a single pass
excellent = {
name: score
for item in raw_data
if (parts := item.split(":")) and (name := parts[0]) and (score := int(parts[1])) >= 90
}
print(excellent) # {'Bob': 92, 'Diana': 95}Warning: chaining multiple walrus operators in the same expression can quickly harm readability. Prefer clarity over excessive conciseness.
Advanced use cases
elif condition chains
The walrus operator is particularly useful when you need to test multiple patterns and act on the first one that matches:
import re
def analyze_command(text):
if (match := re.match(r"create (\w+)", text)):
return f"Creating {match.group(1)}"
elif (match := re.match(r"delete (\w+)", text)):
return f"Deleting {match.group(1)}"
elif (match := re.match(r"modify (\w+)", text)):
return f"Modifying {match.group(1)}"
else:
return "Command not recognized"
print(analyze_command("create project")) # Creating project
print(analyze_command("delete account")) # Deleting accountThis pattern with def avoids creating temporary variables before each condition, making the code more fluid.
Data validation
The walrus operator can simplify validation chains:
def validate_registration(name, email, age):
errors = []
if (length := len(name)) < 2:
errors.append(f"Name is too short ({length} character(s))")
if (pos := email.find("@")) == -1:
errors.append("Email does not contain @")
elif not email[pos + 1:]:
errors.append("Email has no domain after @")
if (age_val := int(age)) < 18:
errors.append(f"Insufficient age: {age_val} years (minimum 18)")
return errors if errors else None
Best practices
The walrus operator is a powerful tool, but like any tool, it should be used judiciously. Here are the essential rules to follow:
When to use the walrus operator
- Eliminate duplication: when you need to use the result of an expression both as a condition and as a value.
- While loops with reading: file reading, user input, sockets, etc.
- Comprehensions with filters: when the
iffilter computes a value reused in the expression. - Regex condition chains: testing multiple patterns in
if/elif. - Performance optimization: avoiding calling an expensive function multiple times.
When to avoid the walrus operator
- When a simple assignment suffices: don't use
:=simply to put everything on one line. - In overly complex expressions: if the expression becomes hard to read, use intermediate variables.
- With multiple side effects: avoid chaining multiple
:=in the same expression. - For top-level assignments: at module level, prefer the classic
=assignment.
The PEP 8 style guide recommends using the walrus operator only when it clearly improves readability or eliminates an obvious duplication.
Common errors and pitfalls to avoid
Forgetting parentheses
The walrus operator has low precedence, which often makes parentheses mandatory:
# ❌ Syntax error or unexpected behavior
if x := get_value() > 0: # x receives the result of get_value() > 0 (a boolean!)
print(x)
# ✅ Correct
if (x := get_value()) > 0: # x receives get_value(), then compared to 0
print(x)
Scope confusion in comprehensions
Variables created by := in a comprehension can have a scope that leaks out:
# The variable 'y' exists after the comprehension!
results = [y for x in range(5) if (y := x * 2) > 4]
print(y) # 8 — the last assigned value is accessible hereThis behavior can be surprising. Be aware that the variable assigned by := in a comprehension is accessible in the enclosing scope, unlike the iteration variable.
Impossible use at statement level
You cannot use := as a simple assignment statement:
# ❌ Syntax error
(x := 10) # Technically valid but useless and discouraged
# ✅ Prefer
x = 10
Compatibility and Python version
The walrus operator was introduced in Python 3.8 (October 2019). If you are working with earlier versions, you will not be able to use it and will get a syntax error.
To check your Python version:
import sys
print(sys.version)
# Or check with __name__
if __name__ == "__main__":
print(f"Python {sys.version_info.major}.{sys.version_info.minor}")The __name__ variable is used here in a classic pattern for checking the script's entry point.
Frequently asked questions
Why is the := operator called "walrus"?
The nickname "walrus" comes from the visual resemblance of the symbol := to the eyes and tusks of a walrus seen from the side. The official name of this feature is "assignment expression", as defined in PEP 572. The walrus nickname became so popular in the Python community that it is now universally recognized.
Does the walrus operator replace the classic = operator?
No, absolutely not. The walrus operator := and the classic assignment = have different roles. The classic assignment = is a statement and remains the standard method for assigning values. The walrus operator := is an expression, designed for specific cases where you need to assign and use a value simultaneously, such as in conditions or loops. You should continue to use = for the vast majority of your assignments.
Does the walrus operator work with structures like tuples and lists?
Yes, the walrus operator works with all Python data types, including tuple and list. You can assign any expression to a variable with :=. However, you cannot do unpacking with the walrus: (a, b := (1, 2)) does not work as you might expect. The walrus assigns the complete expression to a single variable.
How can I properly learn to use the walrus operator in Python?
To master the walrus operator and all of Python's advanced features, regular practice is essential. Start with simple cases like while loops with reading, then progress to list comprehensions and condition chains. We recommend following our dedicated Python course which covers these advanced concepts in detail with practical exercises to solidify your skills.