Does order matter when using plus equals?

Hello everyone,

In the context of this exercise,
https://www.codecademy.com/courses/learn-python-3/lessons/python-functions-dictionaries-cc/exercises/sum-values, it looks like order in the += statement of the function matters:

def sum_values(my_dictionary):

  count = 0 

  for value in my_dictionary.values():

    count += value

  return count

If I change the order to value += count, I do not get the same result as when typing count += value.

Why is that?

Thanks in advance!

When you do count += value what you’re telling the computer is:

count = count + value

You’re telling the program to add value to the value stored in count, then assign the new value to count. So, would it make sense just to write += count? What are you adding count to? Sorry if I’ve misread your question.

As @codeneutrino explained,


The same goes for value += count. What you’re really doing is value = value + count. Therefore, it does matter which variable you’re putting before and which variable you’re putting after the += operator. The variable to the left of the operator has its value changed to its current value plus whatever expression is on the right side of the += operator.

1 Like

Many thanks, that made it clear!

1 Like