Working of ‘+=’ operator in Python with examples
In this tutorial, we will learn the working of ‘+=’ operator in Python using some basic examples.’+=’ is a shorthand addition assignment operator. It adds two values and assigns the resultant value to a variable (left operand).
is equivalent to
Let us look into the following three examples and understand the working of this operator.
+= operator – Adding two numeric values in Python
In this example, we initialize a variable x with value 2 and then add value 10 to it and store the resultant value in x.
x=2 x+=10 print(x)
Example 2 – Adding two strings using += operator in Python
In this example, we initialize the variables str1 and str2 with strings “Hello” and ” World” respectively and then add the two strings. ‘+’ operator concatenates the values of the operands which are of string type.
str1 = "Hello" str2 = " World" str1+=str2
Example 3 – Associativity of ‘+=’ operator
The associativity of ‘+=’ operator is from right to left. Operator associativity determines the direction in which the operators having the same precedence evaluate the sub-expressions while operator precedence determines the order in which the sub-expressions are evaluated.
In example 3.1, we initialize two variables x and y with values 3 and 10 respectively. We right shift the value of variable y by 1 bit and add the result to x and store the final result to the same. The precedence of ‘>>’ operator is lower than that of ‘+’ operator. Therefore, had it not been due to the right to left associativity of ‘+=’ operator, the addition operation would have been evaluated first and then the right shift operation which is shown in example 3.2.
x=3 y=10 x+=y>>1
x=3 y=10 x=x+y>>1