In a lot of languages a = a + b can be written as a += b In case of numerical operations, a + b is same as b + a, so the single compound operator suffices.
Also, a = a - b can be written as a -=b .
However, a-b is not equal to b-a. Hence, the compound assignment operator does not work for a = b - a
So, are there compound assignment operators for the operation a = b op a (where op can be +, -, *, /, %, and order matters) ?
[Non commutative operations]
No, there is not.
I suspect this shorthand to come from assembly language where the ADD
instruction does exactly that - takes two operands, makes an addition and stores it to the first one.
I'd say people were used to think this way and so this pattern appeared also in C language as a += b
shorthand. Other languages took this from C.
I think there is no special reason to have or not to have a = a + b
or a = b + a
. I think none of them two is more often needed in programming. The reason is historical. The same why we use QWERTY keyboard layout and not the others.
Update: See this, it is a myth, because C was based on B language rather than coming from assembly languages. The origin is not clear.
+=
.+=
kind of operation rather than a = b + a
, so they were okay with the fact no shorthand existed and did not requested it.The best possible solution is to just write a = b + a
, because it is clear and readable from the first glance. For the same reason (readability) (Update: who knows?) Python does not provide a++
known from C and other languages. You have to type a += 1
. The +=
shorthand is not very readable to a programming beginner neither, but one can still somehow at least guess what is about. It is compromise between tradition, laziness and readability.
If there is no tradition, readability should win, at least in Python. So one should clearly write a few characters more rather than looking for a shorthand. That is the case for a = b + a
.
If you are concatenating more strings, you should watch for .join()
for the performance concern.