The walrus operator in Python has been a somewhat useful yet controversial improvement. In this article, we will discuss the basics of the walrus operator using conditional statements and loops. We will also discuss the python walrus operator controversy that even led to Guido van Rossum stepping down from his honorary position as BDFL (Benevolent Dictator For Life).
What is Python Walrus Operator?
The walrus operator “:=”
is an operator used to evaluate, assign, and return value from a single statement in Python. It was introduced in Python 3.8 and has the following syntax.
(variable:=expression)
Here,
variable
is the variable name.- The
expression
can be any function, arithmetic expression, container objects like lists and sets, or objects of primitive data types such as integers, strings, and floating point numbers. - The
“variable:=expression”
statement must be enclosed inside parentheses. Otherwise, the program will run into an error.
You can use the walrus operator to define a variable and return a value at the same time as shown below.
myVar=(value:=1117)
print("myVar:{}".format(myVar))
print("value:{}".format(value))
Output:
myVar:1117
value:1117
In the above example, we have used the statement myVar=(value:=1117)
to create two variables myVar
and value
. Here,
- The expression
(value:=1117)
uses the walrus operator to define the variablevalue
. It then returns the value outside the parenthesis as if the whole statement(value:=1117)
were a function. - We use the return value from the expression
(value:=1117)
to initialize the variablemyVar
. - In the output, you can observe that both variables have the same value.
If you use the walrus operator outside the parentheses, the program will run into SyntaxError Exception saying that the code you have written isn’t in the correct format. You can observe this in the following code.
value:=1234
Output:
value:=1234
^
SyntaxError: invalid syntax
In the above example, you can observe that the Python interpreter shows SyntaxError in our code because we haven’t enclosed the statement with the walrus operator inside parentheses.
Now, let us discuss some of the use cases of the walrus operator. In this article, we will use the walrus operator with an if statement, for loop, list comprehension, and a while loop in Python.
Python Walrus Operator With If Statement
We can use the walrus operator with an if statement if we want to perform a certain operation on an unknown variable. For example, suppose that the user inputs a list. You need to print the length of the list if its length is greater than 5. Otherwise, your code should do nothing. You can implement this logic using a simple assignment operator and the len() function as shown below.
myList=[1,2,4,5,6,6,89]
length=len(myList)
if length>=5:
print("The length of the list is:",length)
Output:
The length of the list is: 7
In the above code, we have first defined a list myList containing integers. Then, we used the len() function to calculate the length of the list and stored it in the length variable. Finally, we check if the variable length has a value greater than or equal to 5 or not to print the value.
We can implement the above logic using the walrus operator in Python as shown below.
myList=[1,2,4,5,6,6,89]
if (length:=len(myList))>=5:
print("The length of the list is:",length)
Output:
The length of the list is: 7
In the above code, the statement (length:=len(myList))
calculates the length of the list and assigns it to the length
variable. It also returns the length of the list which is then compared using the comparison operator.
Here, you can observe that we have initialized and compared the value in the length
variable in a single statement using the walrus operator.
Python Walrus Operator in For Loop
Just like an if statement, we can also use the Python walrus operator in for loop in many cases. For example, suppose that you are given a list of numbers. You need to create a list of squares of numbers in the input list if the squares are greater than 100. For this, we can write a Python program as shown below.
myList=[1,2,7,5,9,6,11, 3, 15]
newList=[]
for val in myList:
square=val**2
if square>=100:
newList.append(square)
print("The original list is:",myList)
print("The output list is:",newList)
Output:
The original list is: [1, 2, 7, 5, 9, 6, 11, 3, 15]
The output list is: [121, 225]
In the above loop, we can use the walrus operator to implement the same logic as shown below.
myList=[1,2,7,5,9,6,11, 3, 15]
newList=[]
for val in myList:
if (square:=val**2)>=100:
newList.append(square)
print("The original list is:",myList)
print("The output list is:",newList)
Output:
The original list is: [1, 2, 7, 5, 9, 6, 11, 3, 15]
The output list is: [121, 225]
Python Walrus Operator in List Comprehension
Now, suppose that we implement the previous example using list comprehension as shown below.
my_list = [1, 2, 3, 4, 5]
new_list = [i ** 2 for i in my_list if i**2>=100]
print("The original list is:",myList)
print("The output list is:",newList)
Output:
The original list is: [1, 2, 7, 5, 9, 6, 11, 3, 15]
The output list is: [121, 225]
We can use the walrus operator with list comprehension as shown below. Here, we don’t need to calculate the square of the numbers twice. Instead, we initialize a variable j using the walrus operator while comparison and use it to create the output list.
my_list = [1, 2, 3, 4, 5]
new_list = [j for i in my_list if (j:=i**2)>=100]
print("The original list is:",myList)
print("The output list is:",newList)
Output:
The original list is: [1, 2, 7, 5, 9, 6, 11, 3, 15]
The output list is: [121, 225]
Python Walrus Operator With While Loop
You can also use the walrus operator with a while loop in Python. To understand this, suppose that you need to generate a random number and print it. The condition here is that if you find the number 5, you need to come out of the while loop.
To implement this, we will create an infinite loop using a while loop. Inside the loop, we will first create a random number using the randint()
function defined in the random module. The randint()
function takes the lower limit and upper limit of a range of numbers and generates a random number between the range. We will pass 1 as the lower limit and 10 as the upper limit.
After generating the random number, we will check if it’s equal to 5. If yes, we will come out of the while loop using a break statement. Otherwise, we will print the number. You can observe this in the following example.
import random
while True:
num = random.randint(1, 10)
if num == 5:
break
else:
print(num)
Output:
1
7
7
6
4
1
7
8
10
We can implement the above logic using the Python walrus operator as shown below.
import random
while (num := random.randint(1, 10)) != 5:
print(num)
Output:
2
3
9
In this example, you can observe that the number of lines in the code is reduced significantly when we use the walrus operator. However, the statement inside the while loop becomes complicated as function calls, assignments, as well as comparisons are being done in a single statement.
Python Walrus Operator Controversy
The walrus operator had received mixed responses when it was launched. Developers were in support of the operator and in against too. Let us discuss some of the points in both cases.
Observations Against The Walrus Operator in Python
The walrus operator violates many heuristics mentioned in the zen of Python. To understand them, let us discuss the following use cases.
Explicit is Better Than Implicit
The Zen of Python says that explicit operations are always better than implicit operations. The walrus operator assigns a value to a variable and implicitly returns the value too. Thus, it doesn’t fit into the idea of “Explicit is better than implicit”
Complex is Better Than Complicated
Using the walrus operator can be complicated in many cases. For instance, consider the following example.
print((x:=3+2/5)>0)
Instead, we can use the following code without using the walrus operator. Here, you can observe that the code is less complicated.
x=3+2/5
print(x>0)
Beautiful is Better Than Ugly
Using the colon operator with the assignment operator and the parentheses outside the statement containing the walrus operator makes the code look a bit dirty. For instance, consider the following example.
(z := (y := (x := 0)))
In the above statement, we have initialized the variables x, y, and z using the walrus operator. Instead, we can use the following code to initialize the variables, which will give the same result.
x = y = z = 0
You can observe that this statement looks more beautiful than the previous statement. Hence, the walrus operator can make your code dirty and violates the heuristics of the Zen of Python.
Readability Counts
Again, when we perform calculations, assignments, and comparisons, as well as return the value in a single statement, the readability of the code decreases. For instance, consider the following statement.
import math
myList=[(y := math.sqrt(100)), y**2, y**3]
In the above code, we have made a function call inside a list to create a list using the walrus operator. It decreases the readability of the code. Instead, we can use the following code without the walrus operator and the result will be the same in addition to improved readability.
import math
y = sqrt(100)
myList=[y, y**2, y**3]
There Should be One and Preferably Only One Obvious Way to Do It
The zen of Python clearly says that there should be only one obvious way to do it. If we can perform assignment and return operations in two different operations, why should we use the less readable and complex statement containing the walrus operator to do the same task? If we consider the obvious choice, the Python walrus operator loses here too.
Statements in Support of The Walrus Operator
The walrus operator can save computation time in some cases. For instance, consider the example we used to explain the walrus operator with a list comprehension. Without the walrus operator, we used the following statement to generate the output list.
new_list = [i ** 2 for i in my_list if i**2>=100]
With the walrus operator, we used the following statement.
new_list = [j for i in my_list if (j:=i**2)>=100]
By comparing the two statements, you can clearly see that the list comprehension containing the walrus operator calculates the square of the numbers in the input list only once. Without the walrus operator, we need to calculate the square of numbers two times. Thus, the walrus operator saves computation costs. It also helps in cases like using loop variables as shown in the example for the while loop.
Should You Use The Walrus Operator in Your Code?
If you ask me, I have never used the Python walrus operator in my code. The reason is that it unnecessarily increases the complexity of the code and makes it less readable. Although in some cases, it can improve the performance of your program, it is always better to stick to the tools that you have mastered. Given that there is no significant difference in the computation efficiency of the code with or without the Python walrus operator, You should not choose to use the walrus operator.
Conclusion
In this article, we discussed the Python walrus operator, its uses, advantages, and disadvantages. To learn more about Python programming, you can read this article on Pyspark vs Pandas. You might also like this article on PyPy vs Pyston.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, I only recommend products or services I use personally and believe will add value to my readers.