Is += a Shortcut for x = x + y?


#1

Is the += command a shortcut to saying: annual_rainfall = annual_rainfall + november_rainfall?


FAQ: Learn Python - Python Syntax - Updating Variables
#2

Hi @oadin,

That’s correct. The += operator is only used because it’s more convenient to type out.


#3

Values can implement += differently if they wish. If the value is mutable then the in-place version likely modifies the value rather than creating a new one.

a = b = []
b += range(3)
print(a)  # [0, 1, 2]
a = b = []
b = b + range(3)
print(a)  # []

#4
>>> b = b + range(3)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    b = b + range(3)
TypeError: can only concatenate list (not "range") to list
>>> b = b + list(range(3))
>>> b
[0, 1, 2, 0, 1, 2]
>>> a
[0, 1, 2]
>>> 

#5

Right. That’s another difference. list’s + doesn’t iterate, but += does

I do wonder why + doesn’t also iterate over the other value


#6

Sorry, I did precurse the above these two lines…

>>> a = b = []
>>> b += range(3)

Which lends itself to your quesiton of the difference. Hmmm?

+ is plus, and concatenate, and nothing more. += (as with any assignment operator) is a method. That enlarges the playing field (my take on it).


#7

+= is in-place add, it stands to reason it does the same thing as + aside from being in-place

I think it (list’s +=) might have been implemented using list.extend’s code and therefore got an extra feature which then couldn’t be removed.
But that’s purely a guess, and I don’t really need a reason

Take for example set’s &=
It doesn’t accept an iterable, neither does |= or ^=
And not str’s +=

list’s += is the odd one out