Posts

Walrus Operator in Python | How to use it.

Estimated read time: 1 min

What is Walrus Operator

The Walrus Operator (:=) in Python, introduced in Python 3.8, is also called the assignment expression operator. It allows you to assign a value to a variable as part of an expression.

How to Use the Walrus Operator

The syntax is:


    variable := expression

Here, the expression is evaluated, and its value is assigned to the variable.

Example 1: Basic Usage


    if (n := len([1, 2, 3, 4, 5])) > 3:
        print(f"List length is {n}, which is greater than 3")

How to Define a Use Case for the Walrus Operator

The Walrus Operator is most effective in situations where:

  • You want to assign and use a variable within a single expression.
  • You aim to reduce redundancy or improve readability by avoiding repeated function calls.

Example 2: Reading Input


    while (line := input("Enter text (or 'exit' to quit): ")) != 'exit':
        print(f"You entered: {line}")

Where Best to Use the Walrus Operator

  1. Loops: When you need to assign a value and check it within a loop.


        while (chunk := file.read(1024)):
            process(chunk)

  2. Conditional Expressions: When you want to avoid redundant calculations.


        if (count := len(data)) > 10:
            print(f"Data count is {count}")

  3. List Comprehensions: To make intermediate results reusable.


        result = [(n, square := n ** 2) for n in range(5) if square > 4]

When to Use

  • Use it when it makes your code clearer or avoids repetitive calculations.
  • Avoid it if it makes the code harder to follow or overly compact.

Good:


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

Bad:


    while (x := get_data()) and (y := process(x)) and (z := finalize(y)):
        print(z)

Conclusion

Use the Walrus Operator when it improves code efficiency and readability but avoid it if it introduces complexity or confusion.

💫Thank you💫

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.