Author's image | Created on Snappify
In Python, if you want to assign values to variables within an expression, you can use the Walrus operator :=. x = 5
is a simple variable assignment, x := 5
This is how you will use the Walrus operator.
This operator was introduced in Python 3.8 and can help you write more concise and potentially more readable code (in some cases). However, using it when it's not necessary or when it's more than necessary can also make your code harder to understand.
In this tutorial, we will explore the effective and not so effective uses of the Walrus operator with simple code examples. Let's get started!
How and When Python's Walrus Operator Is Useful
Let's start by looking at examples where the walrus operator can improve your code.
1. More concise loops
It is quite common to have loop constructs where an input is read to be processed inside the loop and the loop condition depends on the input. In such cases, using the walrus operator helps to keep the loops cleaner.
Without walrus operator
Let's consider the following example:
data = input("Enter your data: ")
while len(data) > 0:
print("You entered:", data)
data = input("Enter your data: ")
When you run the above code, you will be repeatedly prompted to enter a value whenever you enter a non-empty string.
Note that there is redundancy. Initially, it reads the input in the data
variable. Inside the loop, the entered value is printed and the user is prompted for input again. The loop condition checks if the string is not empty.
With the operator Walrus
You can remove the redundancy and rewrite the previous version using the walrus operator. To do this, you can read the input and check if it is a non-empty string (all within the loop condition) using the walrus operator as follows:
while (data := input("Enter your data: ")) != "":
print("You entered:", data)
This is now more concise than the first version.
2. Better understanding of lists
Function calls are sometimes included inside list comprehensions. This can be inefficient if there are multiple expensive function calls. In such cases, rewriting with the walrus operator can be useful.
Without walrus operator
Let's take the following example where there are two calls to the `compute_profit` function in the list comprehension expression:
- To fill the new list with the value of the profit and
- To check if the profit value is above a specified threshold.
# Function to compute profit
def compute_profit(sales, cost):
return sales - cost
# Without Walrus Operator
sales_data = ((100, 70), (200, 150), (150, 100), (300, 200))
profits = (compute_profit(sales, cost) for sales, cost in sales_data if compute_profit(sales, cost) > 50)
With the operator Walrus
You can assign the return values of the function call to the variable `profit` and use it to populate the list like this:
# Function to compute profit
def compute_profit(sales, cost):
return sales - cost
# With Walrus Operator
sales_data = ((100, 70), (200, 150), (150, 100), (300, 200))
profits = (profit for sales, cost in sales_data if (profit := compute_profit(sales, cost)) > 50)
This version is better if the filter condition involves an expensive function call.
How not to use Python's Walrus operator
Now that we've seen some examples of how and when Python's walrus operator can be used, let's look at some antipatterns.
1. Understanding complex lists
In a previous example, we used the walrus operator inside a list comprehension to avoid repeated function calls. But overusing the walrus operator can be just as bad.
The following list comprehension is difficult to read due to multiple nested conditions and assignments.
# Function to compute profit
def compute_profit(sales, cost):
return sales - cost
# Messy list comprehension with nested walrus operator
sales_data = ((100, 70), (200, 150), (150, 100), (300, 200))
results = (
(sales, cost, profit, sales_ratio)
for sales, cost in sales_data
if (profit := compute_profit(sales, cost)) > 50
if (sales_ratio := sales / cost) > 1.5
if (profit_margin := (profit / sales)) > 0.2
)
As an exercise, you can try breaking up the logic into separate steps (inside a regular loop and in conditional statements). This will make the code much easier to read and maintain.
2. Nested Walrus Operators
Using nested walrus operators can result in code that is difficult to read and maintain. This is particularly problematic when the logic involves multiple assignments and conditions within a single expression.
# Example of nested walrus operators
values = (5, 15, 25, 35, 45)
threshold = 20
results = ()
for value in values:
if (above_threshold := value > threshold) and (incremented := (new_value := value + 10) > 30):
results.append(new_value)
print(results)
In this example, nested walrus operators make understanding difficult because they require the reader to unpack multiple layers of logic within a single line, which reduces readability.
Ending
In this quick tutorial, we go over how and when to use and when not to use Python's walrus operator. You can find the code examples on GitHub.
If you're looking for common mistakes to avoid when programming with Python, read 5 Common Python Mistakes and How to Avoid Them.
Keep coding!
twitter.com/balawc27″ rel=”noopener”>Bala Priya C. Bala is a technical developer and writer from India. She enjoys working at the intersection of mathematics, programming, data science, and content creation. Her areas of interest and expertise include DevOps, data science, and natural language processing. She enjoys reading, writing, programming, and drinking coffee! Currently, she is working on learning and sharing her knowledge with the developer community by creating tutorials, how-to guides, opinion pieces, and more. Bala also creates interesting resource overviews and coding tutorials.
<script async src="//platform.twitter.com/widgets.js” charset=”utf-8″>