Assignment Expressions

Assignment expressions, also known as the "walrus operator" (`:=`), were introduced in Python 3.8. They allow you to assign a value to a variable within an expression, providing more concise and readable code. This operator is particularly useful in scenarios where you want to both use and assign a value at the same time.

Benefits

Reduced Code Duplication: You can avoid writing the same expression multiple times.

Improved Readability: It can make certain patterns clearer, especially when filtering or looping through data.

Considerations

Readability: While they can make some code cleaner, overusing assignment expressions might lead to less readable code, especially for those unfamiliar with the syntax.

Scope: The variable assigned with := is scoped to the block in which it is used.

1. Basic Syntax of Assignment Expressions

The assignment expression `:=` allows you to assign a value to a variable while using it within the same line.

Example: Using `:=` in an `if` statement.
# Using an assignment expression to both assign and check a value
if (n := 10) > 5:
    print(f"n is {n}, which is greater than 5")

# Output: n is 10, which is greater than 5

Output:
n is 10, which is greater than 5

Explanation: In this example, `n` is assigned the value `10` within the `if` statement using the assignment expression `n := 10`. The condition `(n := 10) > 5` both assigns `10` to `n` and evaluates if `n` is greater than `5`. The output confirms that the value of `n` is correctly assigned and checked in a single expression.

2. Using Assignment Expressions in Loops

Assignment expressions are particularly useful in loops where you need to use a value repeatedly within a condition.

Example: Reading user input in a loop until a condition is met.
# Using an assignment expression in a while loop
while (user_input := input("Enter a number (or 'q' to quit): ")) != "q":
    print(f"You entered: {user_input}")

# Output example:
# Enter a number (or 'q' to quit): 5
# You entered: 5
# Enter a number (or 'q' to quit): q

Output:
Enter a number (or 'q' to quit): 5
You entered: 5
Enter a number (or 'q' to quit): q

Explanation: In this example, the assignment expression `user_input := input(...)` assigns the result of `input` directly within the `while` condition. This approach allows the input to be assigned and checked for equality with "q" in the same line. The output shows that the program repeatedly prompts the user for input until "q" is entered.

3. Assignment Expressions with List Comprehensions

Assignment expressions can also be used within list comprehensions, improving the readability and efficiency of the code.

Example: Filtering a list while simultaneously performing calculations.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Using an assignment expression in a list comprehension
squares = [square for n in numbers if (square := n ** 2) > 20]

print(squares)  # Output: [25, 36, 49, 64, 81]

Output:
[25, 36, 49, 64, 81]

Explanation: Here, we use `square := n ** 2` in the list comprehension to calculate the square of `n` and filter out values less than or equal to 20. This prevents the need to calculate the square twice and makes the code more efficient. The output confirms that only squares greater than 20 are included in the final list.

4. Using Assignment Expressions with Functions

Assignment expressions can be used to store function return values directly within expressions, which is particularly helpful for simplifying code.

Example: Assigning the return value of a function in an `if` condition.
def get_value():
    return 42

# Using an assignment expression with a function call
if (result := get_value()) > 40:
    print(f"Result {result} is greater than 40")

# Output: Result 42 is greater than 40

Output:
Result 42 is greater than 40

Explanation: The assignment expression `result := get_value()` calls `get_value()` and assigns the return value to `result` in the `if` condition. This eliminates the need for a separate line to store the function's return value, making the code more concise. The output shows that the assignment and condition check work correctly.

5. Assignment Expressions in Nested Data Structures

Assignment expressions can simplify working with complex or nested data structures by reducing the number of lines needed for assignments and checks.

Example: Extracting specific values from a dictionary of lists.
data = {"values": [10, 20, 30, 40, 50]}

# Using an assignment expression to access and filter nested data
if (vals := data.get("values")) and (filtered_vals := [v for v in vals if v > 25]):
    print(f"Filtered values: {filtered_vals}")

# Output: Filtered values: [30, 40, 50]

Output:
Filtered values: [30, 40, 50]

Explanation: In this example, `vals := data.get("values")` assigns the list of values if it exists in `data`. `filtered_vals := [v for v in vals if v > 25]` further filters out values less than or equal to 25. The output shows the successfully filtered list, confirming that assignment expressions can make working with nested data more concise.

6. Using Assignment Expressions in Nested Loops

Assignment expressions can be particularly useful in nested loops, where you want to avoid repeated calculations.

Example: Processing elements in a nested list.
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Using assignment expressions to process each row
for row in matrix:
    if (row_sum := sum(row)) > 10:
        print(f"Row with sum > 10: {row}, sum: {row_sum}")

# Output:
# Row with sum > 10: [4, 5, 6], sum: 15
# Row with sum > 10: [7, 8, 9], sum: 24

Output:
Row with sum > 10: [4, 5, 6], sum: 15
Row with sum > 10: [7, 8, 9], sum: 24

Explanation: In this example, we use `row_sum := sum(row)` to calculate and assign the sum of each row directly within the `if` condition. This approach prevents the need to calculate the sum twice and simplifies the code. The output confirms that only rows with sums greater than 10 are printed.

7. Conclusion

The assignment expression (`:=`) offers a powerful way to assign and use values within a single line. By reducing redundant lines of code, it enhances readability, especially in loops, conditionals, list comprehensions, and with nested data structures. Through these scenarios, assignment expressions demonstrate their versatility in making Python code more concise and expressive.

Previous: Python TypedDict | Next: Python f-String

<
>