Introduction
The Python walrus operator :=
(named for its resemblance to the eyes and tusks of a walrus when viewed sideways) assigns a value to a variable. But unlike assignment operator =
, it also returns the assigned value.
This extra feature makes it into an expression, which is a construct that produces a value. It allows the walrus operator to be used in contexts where an assignment and a value are both needed, such as within a conditional statement, loops and comprehensions.
The walrus operator is a relatively new addition to Python and was introduced in version 3.8.
Using the Walrus Operator
The walrus Operator :=
allows you to assign a value to a variable as part of an expression. This operator is particularly useful in situations where you want to both assign a value and immediately use it within the same expression.
Here is the basic syntax for the walrus operator:
variable := expression
Example:
n = 7 if (square := n**2) > 42: print(f"The square of {n}, which is {square}, is greater than 42.")
Output:
The square of 7, which is 49, is greater than 42.
In the example above, square
is assigned the value of n**2
(n squared) and immediately checked to see if it’s greater than 42 (line 2). If it is, the print
statement (line 3) can use the value of the square without recomputing it, and without assigning square
in a separate statement before the if
.
Walrus Operator in Loops
The walrus Operator can streamline loop conditions by combining assignment and evaluation. This can be particularly useful in while
loops where a value is assigned and checked in each iteration.
Example:
message = ["Stop", "at", "the", "period", "."] while (word := message.pop(0)) != ".": print(f"Reading the word: {word}")
Output:
Reading the word: Stop Reading the word: at Reading the word: the Reading the word: period
In the example above, word
is assigned the result of data.pop(0)
, which removes the first item of the list and returns it. word
is immediately checked against the string “.
” to make the loop terminate when a period is encountered.
Walrus Operator With Comprehensions
The Walrus Operator can be used in comprehensions to avoid redundant calculations within the comprehension. The next example demonstrates its use within a list comprehension.
Example:
values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] squared = [y for x in values if '1' in str(y := x**2)] print(squared)
Output:
[1, 4, 9, 16, 25]
The list comprehension in the example above creates a list of square integers that have the digit 1 in them. In the comprehension expression, y
is assigned x**2
in the if
filter, and also used in the output expression for inclusion in the resulting list, avoiding redundant calculations (line 2).
Note that Python checks the filter condition first. Consequently, the walrus operator assignment must be there so that the variable can be used in the output expression later. Namely, in the previous example,
[y := x**2 for x in values if '1' in str(y)]
would not work.
Pros and Cons of the Walrus Operator
Pros
- Enhanced Readability: The walrus operator can make the code more readable by consolidating assignment and conditional logic into a single line. This can make it easier to understand what the code is doing at a glance.
- Improved Performance: By avoiding multiple evaluations of the same expression, the walrus operator can lead to slight performance improvements in cases where the same value is used multiple times in a comprehension, condition or loop.
Cons
- Readability Trade-offs: In some cases, especially in more complex expressions, using the walrus operator might make the code harder to read compared to using separate assignment statements. It’s important to balance its use to maintain overall code clarity.
- Learning Curve: For new Python programmers or those unfamiliar with the walrus operator, it can add a layer of complexity to the language. Understanding its proper use and potential pitfalls requires a good grasp of Python’s evaluation and assignment mechanics.
- Limited Use Cases: While the walrus operator is useful, its use cases are relatively niche. It shines in specific scenarios but doesn’t offer significant benefits in all coding situations.
Summary & Reference for the Python Walrus Operator
The walrus operator :=
in Python allows for assignment expressions. It enables variables to be assigned values, and the value to be used as part of an expression.
n = 7 if (square := n**2) > 42: print(f"The square of {n}, which is {square}, is greater than 42.")
The basic syntax for the Walrus Operator is:
variable := expression
In loops, it can combine assignment and evaluation:
message = ["Stop", "at", "the", "period", "."] while (word := message.pop(0)) != ".": print(f"Reading the word: {word}")
In list comprehensions, it avoids redundant calculations:
values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] squared = [y for x in values if '1' in str(y := x**2)] print(squared)
The walrus operator is a powerful addition to Python that, when used properly, can enhance code readability and efficiency. However, it should be used judiciously to avoid potential drawbacks related to complexity and clarity.