The Walrus operator (:=), introduced in Python 3.8, is a powerful feature that allows you to assign a value to a variable as part of an expression. This operator often makes code more concise, readable, and efficient, especially in conditions and loops.


Basic Syntax

The Walrus operator is written as :=, combining assignment (=) and expression evaluation.

Practical Example Without Walrus Operator

number = input("Enter a number: ")
if int(number) > 10:
    print("The number entered is greater than 10")
else:
    print("The number entered is less than or equal to 10")

Refactored Example Using Walrus Operator

if (number := int(input("Enter a number: "))) > 10:
    print("The number entered is greater than 10")
else:
    print("The number entered is less than or equal to 10")

What's improved?

  • We assign and evaluate number inside the if condition.

  • No need for a separate assignment line.

More Practical Use Cases

1. Using Walrus in a while Loop

Efficiently capturing user input until a condition is met:

while (number := input("Enter a number (0 to exit): ")) != "0":
    print(f"You entered: {number}")

2. Reading Lines from a File

Instead of reading the file twice (once to check, once to assign):

with open("data.txt") as file:
    while (line := file.readline().strip()):
        print(f"Line: {line}")

3. Processing User Input in Loops

Collect only valid positive numbers:

numbers = []
while (num := int(input("Enter a positive number (or -1 to stop): "))) != -1:
    if num > 0:
        numbers.append(num)
print(f"Collected numbers: {numbers}")

4. Efficient List Comprehensions

Avoid calculating values multiple times:

values = [val for item in range(10) if (val := item * 2) > 10]
print(values)

Here, val is calculated once and reused, making the code both faster and cleaner.

Common Mistakes to Avoid

  • Remember that := is not a replacement for = everywhere. It's specifically for expressions inside conditions or comprehensions.

  • Make sure to not overuse it where traditional assignment would be clearer.


Summary

The Walrus operator (:=) makes Python code:

  • More concise

  • More readable (when used properly)

  • More efficient in scenarios like loops, conditionals, and comprehensions.

Start using it in small cases to get familiar, and soon you’ll wonder how you lived without it!


⚡ Quick Tip: Always balance readability. If using := makes your code harder to understand, a classic assignment might still be better!

Copyright Notice: Unless otherwise indicated, all articles are original to this site, and reproduction must cite the source

Article link:http://pybeginners.com/article/what-is-the-walrus-operator-in-python/