Walrus Operator in Python
In the python 3.8 release, a new assignment operator was introduced which became wildly famous because of its being controversial and Guido van Rossum (creator of python) stepping down as BDFL (Benevolent dictator for life) “key visionary” “final decider” of the python language updates.
The Walrus operator :=
The name “walrus” because it resembles the eyes and tusk of a walrus.
The update introduces a new syntax := to assign value to a variable as a part of a larger expression.
Let’s understand what does a “Walrus operator” do with an example.
Make sure your python version is updated to version 3.8 or above. [jump to code implementation]
Traditional way before python version 3.8
In the above code, a list is created first and then it is passed as an argument to the print function. If a function with
Walrus way after python version 3.8
print(my_list:=[1,2,3,4,5,6]) #variable initialzed in the argument print(my_list) #variable is saved
By using the walrus operator you can avoid initializing a variable before passing it as an argument but instead, we can initialize it using the walrus operator right in the argument.
Additionally, the variable initialized by the walrus operator can be reused further in the program.
Walrus operator in while loops
To demonstrate how walrus operator can be used in while loop we will write a program which stores all the input by the user until the user enters quit .
#list to store all inputs list_of_inputs= #ask input from user x=input("Enter something") #while loop checks if input is not quit while (x!="quit"): #append input in list of inputs list list_of_inputs.append(x) #print list of inputs print(list_of_inputs) #again asks the user to input something x=input("Enter something")
#list to collect inputs list_of_inputs= #initialize a new variable x in every iteration until the user input quit while (x:=input("Enter something")) != "quit": #append the user input in list list_of_inputs.append(x) #print the list of all inputs print(list_of_inputs)
By using the walrus operator we have reduced the usage of writing the input function twice.
Showcase your project and insights with our audience.
Email us at electroic321 [at] gmail [dot] com