Sign In
Sign In

The Walrus Operator in Python

The Walrus Operator in Python
Hostman Team
Technical writer
Python
23.10.2024
Reading time: 4 min

The first question newcomers often ask about the walrus operator in Python is: why such a strange name? The answer lies in its appearance. Look at the Python walrus operator: :=. Doesn't it resemble a walrus lounging on a beach, with the symbols representing its "eyes" and "tusks"? That's how it earned the name.

How the Walrus Operator Works

Introduced in Python 3.8, the walrus operator allows you to assign a value to a variable while returning that value in a single expression. Here's a simple example:

print(apples = 7)

This would result in an error because print expects an expression, not an assignment. But with the walrus operator:

print(apples := 7)

The output will be 7. This one-liner assigns the value 7 to apples and returns it simultaneously, making the code compact and clear.

Practical Examples

Let’s look at a few examples of how to use the walrus operator in Python.

Consider a program where users input phrases. The program stops if the user presses Enter. In earlier versions of Python, you'd write it like this:

expression = input('Enter something or just press Enter: ')

while expression != '':
    print('Great!')
    expression = input('Enter something or just press Enter: ')

print('Bored? Okay, goodbye.')

This works, but we can simplify it using the walrus operator, reducing the code from five lines to three:

while (expression := input('Enter something or just press Enter: ')) != '':
    print('Great!')

print('Bored? Okay, goodbye.')

Here, the walrus operator allows us to assign the user input to expression directly inside the while loop, eliminating redundancy.

Key Features of the Walrus Operator:

  • The walrus operator only assigns values within other expressions, such as loops or conditions.
  • It helps reduce code length while maintaining clarity, making your scripts more efficient and easier to read.

Now let's look at another example of the walrus operator within a conditional expression, demonstrating its versatility in Python's modern syntax.

Using the Walrus Operator with Conditional Constructs

Let’s write a phrase, assign it to a variable, and then find a word in this phrase using a condition:

phrase = 'But all sorts of things and weather must be taken in together to make up a year and a sphere...'
word = phrase.find('things')
if word != -1:
    print(phrase[word:])

The expression [word:] allows us to get the following output:

things and weather must be taken in together to make up a year and a sphere...

Now let's shorten the code using the walrus operator. Instead of:

word = phrase.find('things')
if word != -1:
    print(phrase[word:])

we can write:

if (word := phrase.find('things')) != -1:
    print(phrase[word:])

In this case, we saved a little in volume but also reduced the number of lines. Note that, despite the reduced time for writing the code, the walrus operator doesn’t always simplify reading it. However, in many cases, it’s just a matter of habit, so with practice, you'll learn to read code with "walruses" easily.

Using the Walrus Operator with Numeric Expressions

Lastly, let’s look at an example from another area where using the walrus operator helps optimize program performance: numerical operations. We will write a simple program to perform exponentiation:

def pow(number, power):
    print('Calling pow')
    result = 1
    while power:
        result *= number
        power -= 1
    return result

Now, let’s enter the following in the interpreter:

>>> [pow(number, 2) for number in range(3) if pow(number, 2) % 2 == 0]

We get the following output:

Calling pow
Calling pow
Calling pow
Calling pow
Calling pow
[0, 4, 16]

Now, let's rewrite the input in the interpreter using the walrus operator:

>>> [p for number in range(3) if (p := pow(number, 2)) % 2 == 0]

Output:

Calling pow
Calling pow
Calling pow
[0, 4, 16]

As we can see, the code hasn’t shrunk significantly, but the number of function calls has nearly been halved, meaning the program will run faster!

Conclusion

In conclusion, the walrus operator (:=) introduced in Python 3.8 streamlines code by allowing assignment and value retrieval in a single expression. This operator enhances readability and efficiency, particularly in loops and conditional statements. Through practical examples, we’ve seen how it reduces line counts and minimizes redundant function calls, leading to faster execution. With practice, developers can master the walrus operator, making their code cleaner and more concise.

Python
23.10.2024
Reading time: 4 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us