Walrus Operator in python 3.8
The
latest change in Python 3.8 is the introduction of assignment
expressions and
they
are written using a new notation (:=
).
This operator is often called the walrus
operator as it is similar to the eyes
and tusks of a walrus on its side.
So we will get to see a new type of operator which is being known as the walrus operator (:=) allows us to assign variables inside an expression. The major benefit of this is to save some lines of code and we can write even cleaner and compact code in Python.
The Assignment expressions allow us to assign and return a value in the same expression. For example, if we want to assign to a variable and print its value, then we typically do something like this:
>>> name = walrus
>>> print(name)
walrus
In Python 3.8, we’re allowed to combine these two statements into one, using the walrus operator:
>>> print(name:=walrus)
walru
The assignment expression allows us to assign walrus to name
, and immediately print the value. But keep in mind that the walrus operator does not do anything that isn’t possible without it. It only makes certain constructs more convenient, and can sometimes communicate the intent of our code more clearly.
Let’s check the below example,
>>>values=list()
>>>while True:
>>> current = input("Write something here: ")
>>> if current == "stop":
>>> break
>>> values.append(current)
Using walrus operator on the above case we can simplify the code as,
>>>values = list()
>>>while (current := input("Write something here: ")) != "stop": values.append(current)
This moves the test back to the while
line, where it should be. However, there are now several things happening at that line, so it takes a bit more effort to read it properly. Use our best judgment about when the walrus operator helps make our code more readable. Hence, using assignment expressions to simplify some code constructs.