What is Walrus Operator in python ? Python 3.8 Version New Features.


                                                                           ðŸ’—

 Each new version of python adds new features to language. for python 3.8 the bigger change is the addition of assignment expression.

Specifically the " := " operator gives you a new syntax for assigning variable in the middle of expression. This operator is colloquially known as the Walrus operator.

The Walrus operator is officially known as the Assignment Expression Operator.

During early discussion it was dubbed the Walrus Operator because the := syntax resembles the eye and tusks of a sideway walrus.

You may also see the walrus operator referred to as the Colan Equals Operator.


SYNTAX=> Variable:=expression

When to use the Walrus Operator=>

                                          You have two options either going with the assignment operator or the Walrus. But both are used in different scenarios. The assignment operator(=) just assign a value to a variable for future use. Whereas the walrus operator (:=) evaluates the walrus operator expression and assign the result to the variable name.

As we mentioned it's great for simplifying the code in the following situations=>

  1. Repeated function calls can make your code slower than necessary.
  2. Repeated statements can make your code hard to maintain.
  3. Repeated calls that exhaust iterators can make your code overly complex
It also simplifying the process of iterating over a list or a dictionary in python. check the code below.

Examples=>
1. Assigning a value to a variable and use it in an expression.

#without walrus operator
        x=5
        if(x>3):
            print(x)

#with walrus operator
         if(x:=5)>3:
             print(x)

2. Assigning a value to a variable and using it in a loop condition

#without walrus operator 
          in=input("Enter quit for quit")
          while in!="quit":
                   print(in)
            
#with walrus operator
         while(in:=input("Enter quit for quit))!="quit":
                   print(in)

3. Assigning a value to a variable and using it in a list comprehension.

#without walrus operator
      numbers=[1,2,3,4,5]
      squares=[]
      for number in numbers:
                square=number**2
                squares.append(square)

#with walrus operator
     numbers=[1,2,3,4,5]
     squares=[square:=number**2 for number in numbers]
     print(squares)

Comments

Popular posts from this blog

Ex Sena corporator shot at in Borivali during live video, shooter dies by suicide ? Let's Find Truth || REPORT

Top ten tourist place over india.

What is Same sex marriage?