Unusual operator in Python code
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.
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.
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.
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
print(x)
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.
Thanks @sasha_sasha ! As I can see, this operator is useful when debugging/refactoring. But what could be other use cases?
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":
do_something()
But be careful, because this can worsen readability. You should find a balance.
By the way, walrus operator is called so because it resembles the walrus on its side.
Just drop us an email to ... Show more