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.
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.
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:
Now let's look at another example of the walrus operator within a conditional expression, demonstrating its versatility in Python's modern syntax.
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.
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!
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.