The Walrus Operator (:=), introduced in Python 3.8, allows you to assign values to variables as part of expressions. This makes your code cleaner, more concise, and often more efficient, especially in loops and conditional statements.

What is the Walrus Operator?

The := operator is nicknamed the "walrus operator" because it looks like the face of a walrus 🦭.
It allows assignment and evaluation in a single expression—something that wasn’t possible before in standard Python syntax.

Before Walrus:

n = len(my_list)
if n > 5:
    print(f"The list has {n} items.")

With Walrus:

if (n := len(my_list)) > 5:
    print(f"The list has {n} items.")

Common Use Cases

1. Reducing Redundancy in Loops

Without Walrus:

line = input("Type something: ")
while line != "exit":
    print(f"You typed: {line}")
    line = input("Type something: ")

With Walrus:

while (line := input("Type something: ")) != "exit":
    print(f"You typed: {line}")

2. Reading Files Line by Line

with open("example.txt") as f:
    while (line := f.readline()):
        print(line.strip())

3. 📊 Counting Elements in a List

names = ["john", "mary", "john", "anna"]
counter = {}

for name in names:
    if (n := name.lower()) in counter:
        counter[n] += 1
    else:
        counter[n] = 1

print(counter)

4. Avoiding Repeated Function Calls

Without Walrus:

if expensive_function(x) > 10:
    result = expensive_function(x)
    print(result)

With Walrus:

if (result := expensive_function(x)) > 10:
    print(result)

Things to Watch Out For

  • Readability: Use wisely. Overusing it can make code harder to read.

  • Compatibility: Only works in Python 3.8 and above.

  • Limitations: Cannot be used in lambda expressions:

# Invalid:
lambda x: (y := x + 1)

When Should You Use It?

Use the walrus operator when:

  • You want to avoid repeating function calls or expressions.

  • You need to assign and evaluate a value at the same time.

  • You want compact and expressive code without hurting readability.

Conclusion

The Walrus Operator is a powerful addition to Python that helps you write cleaner and more efficient code when used properly. Now that you understand how it works, start using it in your own projects to reduce redundancy and simplify your logic! 

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

Article link:http://pybeginners.com/article/walrus-operator-in-python-with-practical-examples/