Unusual operator in Python code

MiwonG1115 report abuse

What is the := operator? I know about = operator (assignment). Also, I know that there are += and -= syntax which also helps to simplify the incrementing/decrementing operations. But I have never seen := before.


Ondrje4 report abuse

It is a so-called "walrus operator". You have never seen it before because it appeared only in Python version 3.8. And it is needed to perform assignment expressions. They allow to assign a value to the variable and return this value immediately.

sasha_sasha report abuse

Probably the example will be useful for you. Suppose you need to assign a value to a variable and print it. Earlier you will have to do this in the following way:

x = 5

Starting from Python 3.8 this can be done in one line:

print(x := 5)

After this, variable x contains 5 as its value and can be used in the code normally.

MiwonG1115 report abuse

Thanks @sasha_sasha ! As I can see, this operator is useful when debugging/refactoring. But what could be other use cases?

BingoB. report abuse __ edited

It can be used for simplifying while loops. Earlier you had to assign a value to the variable that is used in the loop. Now you can do something like this:

while (a := input("Enter the value"))  != "End":

But be careful, because this can worsen readability. You should find a balance.

JuneMOOre report abuse

By the way, walrus operator is called so because it resembles the walrus on its side.

Add Answer

Need support?

Just drop us an email to ... Show more