How to use the Walrus Operator := in Python
Graham Waters
Master's in Strategic Analytics with Python, Education, and Prompt Engineering Experience
Use the walrus operator (:=) to simplify code with complex expressions.
The walrus operator, introduced in Python 3.8, allows you to assign values to variables within an expression. It can be particularly useful in situations where you need to evaluate a complex expression and reuse its result multiple times.
Here's an example:
import random
# Generate a random number and check if it is greater than 0.5
if (random_num := random.random()) > 0.5:
? ? print(f"{random_num} is greater than 0.5")
else:
? ? print(f"{random_num} is less than or equal to 0.5")
In the above code, the walrus operator := is used to assign the random number generated by random.random() to the variable random_num. This allows you to both evaluate the random number and check its value in a single line.
The walrus operator can be particularly handy when working with loops or complex conditionals, as it reduces the need for redundant calculations.
import random
# Generate random numbers until one is less than 0.1
while (random_num := random.random()) >= 0.1:
? ? print(f"{random_num} is greater than or equal to 0.1")
print(f"{random_num} is less than 0.1")
Isn't that cool?
Happy Friday!