Python walrus operator (Python 3.8 assignment expression)
The “Python walrus operator”, officially known as the assignment expression operator, was introduced in Python 3.8. It’s symbolized by a colon followed by an equal sign :=
.
The Python community refers to it as the “walrus operator” due to its resemblance to a pair of eyes and tusks, like that of a walrus.
The Need for the Walrus Operator
Before the introduction of the walrus operator, Python developers had to assign values to variables in one line and use them in comparisons in the next.
This often resulted in multiple lines of code for simple operations.
# Python code without using the walrus operator value = 10 if value > 5: print(value)
Output
10
In this code snippet, we had to write two lines to assign the value and then use it for comparison.
The walrus operator allows developers to assign and use variables within the same expression.
Syntax of the Walrus Operator
The syntax of the walrus operator is relatively straightforward. It involves a variable, a walrus operator :=
, and an expression.
Remember to enclose the assignment expression in parentheses.
# Using the walrus operator to assign a value and return it (value := 10)
Output
10
In this case, the walrus operator assigns the value 10
to value
and also returns the value 10
. However, remember that you can’t use this operator in a stand-alone statement, unlike the standard assignment operator =
.
Using in If Statements and While Loops
The walrus operator can be used in if
statements and while
loops to make the code more concise. Here’s how to use the walrus operator in if
statements.
input_value = "Hello" if (value := len(input_value)) > 4: print(f"The length of the string is {value}")
Output:
The length of the string is 5
In this example, the walrus operator is used to assign the length of input_value
to value
and compare it with 4
in the same line.
As the length of the string “Hello” is 5
, which is greater than 4
, the message is printed.
You can also use the walrus operator in while
loops to make the code more concise:
# Reading a user input until a non-empty string is entered while (value := input("Enter a non-empty string: ")) == "": print("The string is empty.") print(f"The non-empty string is '{value}'")
Output:
Enter a non-empty string: The string is empty. Enter a non-empty string: Hello The non-empty string is 'Hello'
In this example, the walrus operator is used to assign the value of input("Enter a non-empty string: ")
to value
and compare it to an empty string ""
.
The loop continues to execute as long as the user enters an empty string.
As soon as a non-empty string is entered, it breaks out of the loop and prints the non-empty string.
Using in List Comprehensions
The walrus operator is handy when working with list comprehensions in Python. This allows for more complex calculations within list comprehensions without calling a function multiple times.
import random numbers = [number for _ in range(10) if (number := random.randint(1, 20)) % 2 == 0] print(numbers)
Output
[10, 14, 6, 16, 10]
In this example, the walrus operator assigns the value of random.randint(1, 20)
to number
and checks if it’s even. If it is, it adds the number to the list. This results in a list of random even numbers.
Walrus Operator with Data Structures
The walrus operator can be effectively used with Python’s data structures like lists, sets, and dictionaries, as well as in comprehensions for these data structures.
# Using walrus operator with a list in a dictionary numbers = [5, 3, 7, 1, 2, 8, 6, 4] description = { "max": (num_max := max(numbers)), "min": (num_min := min(numbers)), } print(description)
Output:
{ 'max': 8, 'min': 1 }
In this example, the walrus operator is used to assign the maximum and minimum values of the numbers
list to the variables num_max
and num_min
within the dictionary comprehension.
When to Use and When Not
While the walrus operator offers many advantages, it should be used judiciously. It’s best suited to situations where using it can make the code more concise without sacrificing readability.
For example, it’s beneficial when a variable needs to be assigned and used in the same line, such as within conditions or list comprehensions.
On the other hand, it may not be suitable for complex expressions, as it can make the code difficult to read and understand.
Similarly, in situations where a stand-alone assignment is needed, the traditional assignment operator =
should be used instead of the walrus operator.
Compatibility and Version Support
The walrus operator is a new operator introduced in Python 3.8. As such, it is not available in Python versions prior to 3.8.
For new projects or projects that are guaranteed to run on Python 3.8 or later, feel free to use the walrus operator whenever it improves your code’s clarity and conciseness.
If you’re working on a project that needs to support older Python versions, you should avoid using the walrus operator or rewrite your code in the new syntax.
Tips for Transitioning from Traditional Python Syntax
Transitioning to use the walrus operator from traditional Python syntax can be straightforward with the following tips:
- Start using the walrus operator in simple use cases like
if
conditions orwhile
loops. - Gradually move to more advanced uses like list comprehensions and function calls.
- Always consider the readability of your code. If the use of the walrus operator makes your code hard to read, it might be better to stick with traditional syntax.
Resource:https://docs.python.org/3/whatsnew/3.8.html
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.