Understanding "+="


#1

I'm not stuck on anything currently, but I'm just interested in the answer to a general question. sometimes when I do something wrong I'll be given an error that says "unsupported operand type(s) for +=: 'int' and 'list'" I understand what I do wrong whenever I get this error, but I'm just curious as to what "+=" means. I don't remember it being a math expression I've used so far in python, & I can't find any explanation anywhere online about it.

if anyone knows I'd be grateful!


#2

Given A, B

A += B

The + in the operator can be viewed as a pseudo function that returns A + B and assigns it back onto A.

When adding together objects in Python the data types must be the same.

stringA += stringB

listA += listB

numericA += numericB

Python supports other operations in the same way

-=
*=
/=
//=
%=
**=

&c.


#3

The data types don't need to be the same for operators, just like other functions the arguments can be of differing types, like float and int or a point in time plus an amount of time.

>>> datetime.datetime.now() + datetime.timedelta(days=36524)
datetime.datetime(2116, 9, 27, 9, 55, 52, 153674)

Other languages often just treat += etc as compound assignment, in python they are separate from their non-assignment counterparts but they do fall back on them if they aren't explicitly defined. In python they are in-place operators, for example += for list will extend the current list rather than create a new one as would happen with the + operator

>>> a = [1]
>>> b = a
>>> b *= 2 # b is not assigned a new list, the existing one is modified in-place
>>> a
[1, 1]

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.