Can't Assign Operator Error

I’m getting an Assign Operator Error for the following code written this way:

for i in range(0,len(hairstyles)):
    prices[i] * last_week[i] += total_revenue

But there is no error when written this way:

for i in range(0,len(hairstyles)):
  total_revenue += prices [i] * last_week [i]

I found this explanation for a similar error in stack overflow:

When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn’t a “container”.

So in the case the “operator” is “+=” and on the left there the interpreted value “i” which is not a “container”. Where as total_revenue is a container and therefore should be on the left-hand side?

Also, why is “i” an interpreted value and not a container?


Assignment is from right to left. There is no operation permitted on the left side.

You are correct in concluding that += is the assignment operator. You are incorrect in your assumption that i is an interpreted value. In your example, i is part of the interpreted value, but i by itself is a variable used as an index for the prices list and last_week list. The interpreted value in your first example is the entire expression on the left side of the assignment operator +=. As you found on stack overflow, you must have a suitable container for the interpreted value on the left side. This rule is not unique to +=. The variable that will contain or more appropriately point to the interpreted value always goes on the left side of the assignment operator ( =, +=, -=, *=, etc.).
Consider this simplified example:

x = 4 #x is the container/variable, 4 is the interpreted value
x = 4 * 2 #x is the container/variable, 4 * 2 after it's interpreted will be 8
4 = x #throws an error: SyntaxError: can't assign to literal

Hope this helps!

1 Like