Introduced in Python 3.8, Assignment Expressions allow you to assign a value to a variable and evaluate that value at the same time. The operator := looks like the eyes and tusks of a walrus lying on its side, hence it is commonly called the “Walrus Operator.”
This article explains the basic syntax of assignment expressions and concrete usage patterns (in if statements, while loops, and list comprehensions) to improve code efficiency and readability.
Difference Between “Statements” and “Expressions” in Assignment
In Python, regular variable assignment (=) is treated as a “Statement.” Statements do not return a value, so they cannot be embedded as part of a calculation expression.
# Example of SyntaxError
# x = (y = 10) + 5
On the other hand, an assignment expression (:=) is treated as an “Expression.” Expressions return a value, so they can be written as part of other operations, function arguments, or conditional expressions.
# Example using assignment expression
# 1. 10 is assigned to y
# 2. (y := 10) as a whole evaluates to 10
# 3. 10 + 5 is calculated, and 15 is assigned to x
x = (y := 10) + 5
print(f"x: {x}")
print(f"y: {y}")
Output:
x: 15
y: 10
Use Case 1: In if Statements (Reusing Results)
If you want to evaluate the return value of a function or a calculation result and then use that value inside the if block, assignment expressions make the code concise.
Traditional Method
You need to assign it to a variable once, then evaluate that variable in the condition.
input_text = "Python Programming"
text_length = len(input_text)
if text_length > 10:
print(f"Text is too long. Length: {text_length}")
Method Using Assignment Expression
By performing the assignment inside the conditional expression, you can combine variable definition and evaluation into one line.
input_text = "Python Programming"
# Assign result of len(input_text) to n, while evaluating n > 10
if (n := len(input_text)) > 10:
print(f"Text is too long. Length: {n}")
The scope of variable n extends outside the if statement, so n can be used in subsequent processing.
Use Case 2: In while Loops (Simplifying Loop Conditions)
This is very effective for patterns like “get a value, and continue processing unless it meets a specific condition,” such as receiving user input or reading data from a file.
Traditional Method
You had to write the same process (like input()) twice—before the loop and inside it—or combine an infinite loop with break.
# Example using infinite loop
while True:
command = input("Enter command (q to quit): ")
if command == 'q':
break
print(f"Command entered: {command}")
Method Using Assignment Expression
Since you can fetch and evaluate the value simultaneously in the while condition, you can eliminate code duplication.
# Using assignment expression
# Assign input to command, loop continues if value is not 'q'
while (command := input("Enter command (q to quit): ")) != 'q':
print(f"Command entered: {command}")
Use Case 3: In List Comprehensions (Reducing Computational Cost)
In list comprehensions, if you want to “filter based on a calculation result and store that result in the list,” assignment expressions save the waste of performing the same calculation twice.
Example: Using Results of Heavy Calculation
Assume a function calculate_heavy_value that performs numerical calculation.
import math
def calculate_heavy_value(num):
"""Some calculation (e.g., cube root)"""
return math.sqrt(num ** 3)
source_data = range(10)
# Traditional Method (Inefficient as calculation runs twice)
# result_list = [calculate_heavy_value(x) for x in source_data if calculate_heavy_value(x) > 5]
# Method Using Assignment Expression
# 1. Execute val = calculate_heavy_value(x)
# 2. Evaluate val > 5
# 3. If condition is met, add val to list
result_list = [val for x in source_data if (val := calculate_heavy_value(x)) > 5.0]
print(f"Result List: {result_list}")
Output:
Result List: [5.196152422706632, 8.0, 11.180339887498949, ...(omitted)]
By holding the calculation result in the variable val inside the if clause and using it as the list element, you can halve the number of function calls.
Summary
- The assignment expression (Walrus Operator
:=) assigns a value to a variable within an expression. - It reduces lines of code and improves readability when retrieving and holding values inside
iforwhileconditions. - In list comprehensions, it contributes to performance improvement by consolidating duplicate calculations.
- Overusing it in complex expressions can reduce readability, so it’s important to use it in appropriate situations.
