Can anyone familiar with Python\'s internals (CPython, or other implementations) explain why list addition is required to be homogenous:
In [1]: x = [1]
In
I believe Python designers made addition this way so that '+' operator stays consistently commutative with regard to result type: type(a + b) == type(b + a)
Everybody expects that 1 + 2 has the same result as 2 + 1. Would you expect [1] + 'foo' to be the same as 'foo' + [1]? If yes, what should be the result?
You have 3 choices, you either pick left operand as result type, right operand as result type, or raise an error.
+= is not commutative because it contains assignment. In this case you either pick left operand as result type or throw. The surprise here is that a += b is not the same as a = a + b. a += b does not translate in English to "Add a to b and assign result to a". It translates to "Add a to b in place". That's why it doesn't work on immutables such as string or tuple.
Thanks for the comments. Edited the post.