Walrus operator

From Python 3.8, a new operator called walrus, which means sea lion, has been added to Python, which is not used much, but it helps to reduce the number of lines of code and optimize it.
This operator is an assignment expression. For example, if you want to initialize a variable, you usually do it like this:

				
					name = "sara"
print(name)
				
			

You can also combine these two expressions using the walrus operator in one expression and write:

				
					print(name := "sara")
				
			

The assignment statement allows you to assign the value “sara” to name and immediately print the value.

One pattern that shows some of the strengths of the walrus operator is loops where you need to initialize and update a variable. For example, the following program asks the user to enter a value each time and Adds that value to the list. As soon as the user enters the “stop” statement, it exits the loop and prints the list:

				
					List = []
while True:
    current = input("Enter something: ")
    if current == "stop":
        break
    List.append(current)
print(List)
				
			

Now, if you use the walrus operator, you can write the program in a simpler way:

				
					List = []
while (current := input("Enter something: ")) != "stop":
    List.append(current)
print(List)