-5

I was wondering what the += operator does in python. What is it used for and why would i use it?

Poly_J
  • 17
  • 4
  • 1
    `x += y` is shorthand for `x = x + y`. You couldn't be bothered to do a google search on "python operators"?? – John Gordon Jun 30 '16 at 03:06
  • Why would i want to use it? – Poly_J Jun 30 '16 at 03:08
  • Because this way you don't have to re-type the first variable name, which means less typing and fewer chances to make a dumb mistake (i.e. what if you meant to type `x1 = x1 + y1` but instead you typed `x1 = y1 + y1`? You might not even notice, and then spend hours or days tracking down the bug.) – John Gordon Jun 30 '16 at 03:13

4 Answers4

1

As many have pointed out, x += y is similar to x = x + y.

One notable difference being that the += operator is an "in-place" operation. So x += y is actually "in-place add". Which means, it modifies the object 'x'.

Whereas x = x + y adds the values of 'x' and 'y' and stores the result (as a new object) in 'x', discarding its previous value. This becomes more important when dealing with objects, custom numerical types or in any user-defined class where the behaviour can be modified internally.

+ calls the object's __add__() method.
+= calls __iadd__().
(It can get more complicated, with __radd__, etc. but I'm glossing over that for now.)

One good reason to use += is: depending on the object type, x += y can be optimised in specific cases, but x = x + y has to create a new object to re-assign to 'x'.

aneroid
  • 12,983
  • 3
  • 36
  • 66
0
a += b 

is similar to :

a = a + b

It also works with other basic signs, for instance :

a *= b

is similar to :

a = a * b
Loïc
  • 11,804
  • 1
  • 31
  • 49
0

The other usage is for string, str += 'defg' is the same as str = str + 'defg'

str = 'abc'
str += 'defg'
print(str)
'abcdefg'
0

This is known as augmented assignment, and it is not peculiar to the Python language. The advantage is not just saved typing. There is a computational advantage, since x+=1 evaluates x only once by x=x+1 evaluates x twice. See https://docs.python.org/2/reference/simple_stmts.html#augmented-assignment-statements

Alan
  • 9,410
  • 15
  • 20