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).

x+=5

is equivalent to

x=x+5

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)

Output:

12

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

Output:

Hello World

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.

3.1 example

x=3
y=10
x+=y>>1

Output:

8

3.2 example

x=3
y=10
x=x+y>>1

Output:

6

Leave a Reply

Your email address will not be published. Required fields are marked *