Skip to Content

What Does := Do In Python? The Walrus Operator

What Does := Do In Python? The Walrus Operator

What does := mean and do in Python?

Since Python version 3.8 the new assignment expression, also known as the walrus operator, enables developers the ability to assign a variable from the result of a function or operation and then have that assigned variable reused elsewhere in the code.

One recent example in my code on this site was halving a string using Python.

With this example I had the option of repeating my code multiple times in the simple one-liner I had created. Here is a copy of that code, and how it would have been handled without using the walrus operator:

>>> my_string = "I'm cut in half"
>>> my_string[:int(len(my_string)/2//1)], my_string[int(len(my_string)/2//1)]:]
("I'm cut", ' in half')

As you can see from the above code it isn’t very DRY (Don’t Repeat Yourself). I had to duplicate the operation where I’m dividing the length of the string into 2.

Now you might rightly think: “Just assign the operation to a variable, and reference the variable in your code” and you would be correct.

Here’s how the above code could be re-written to adhere to the DRY principle by not repeating ourselves:

>>> my_string = "I'm cut in half"
>>> n = int(len(my_string)/2//1)
>>> my_string[:n], my_string[n:]
("I'm cut", ' in half')

The code above looks a lot more decent than the first example, doesn’t it?

But just as I assigned that operation to a variable n, I could have easily done the same thing by embedding it into that same line where the main operation was done.

Like so:

>>> my_string = "I'm cut in half"
>>> my_string[:(n:=int(len(my_string)/2//1))], my_string[n:]
("I'm cut", ' in half')

The code still performs exactly the same way as previous, except now I’ve been able to embed the operation where I’m getting half the length of the string into the same variable n and re-using it later in my code.

Can n be used outside this statement?

Yes, if I wanted to reuse n again in my code it isn’t bound by the scope where it is instantiated.

>>> my_string = "I'm cut in half"
>>> my_string[:(n:=int(len(my_string)/2//1))], my_string[n:]
("I'm cut", ' in half')
>>> n
7

Summary

Therefore, the new walrus operator allows developers the ability to assign the result of an operation to a variable that can be used elsewhere within your code.