How does `+=` work?

Hey I’m just wondering. I didn’t know how to complete the last part of this exercise because I think it’s the first time I see the “+=” operator. Maybe I’m wrong?

First time, but not the last. If we query assignment operators in search we find this to be among them.

It happens in two steps. The addition operation is performed where we take the current value and add the new value to it arriving at a new current value once it is assigned back to the variable.

new_current_value = old_current_value + new_value

a = a + b

Both statements above express the same thing.

a += b

expresses it in more succinct terms.


2 posts were split to a new topic: Why += and not append?

2 posts were split to a new topic: Need explanation of output

10 posts were split to a new topic: Why did the pace of the exercises started to go so fast?

I find myself easily switching up =+ and += by mistake. As we’ve been taught what += is for in the course, I was surprised to see that =+ apparently has an alternate task.

Am I mistaking or is there a place and time for both of these operators - if so, could somebody please elaborate?


sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]

scoops_sold = 0

for location in sales_data:
  for scoops in location:
    scoops_sold += scoops

I get either 13 or 96 as a final value for scoops_sold, depending on the operator-formation I use…

Thanks for any replies in advance! :slight_smile:

1 Like

There is no such operator that puts the equal sign first. The operation is always before the assignment.

1 Like

say for instance you are doing following -
x = x + y , (y can be anything a number , variable , but compatible with the datatype of x)
the alternate way to write this is -
+= , where we first mention ‘+’ operator for the operation to be performed and then ‘=’ to assign the result to the variable on the left hand side.

we usually do this , when we are adding something to a variable and want to store the result in the same variable. Other similar operators are -

‘-=’ - for ,say we want do x = x - 2
‘*=’ for, say we want to do x = x * 2


thanks that is good to know!

1 Like

Thank you for the succinct explanation.

Signed n00b