3 ms·
The difference is because + in Python is intended to be a reflexive, declarative operator while += is a directional, imperative operator. If the + has heteroge
by dragonwriter 8y ago
The difference is because + in Python is intended to be a reflexive, declarative operator while += is a directional, imperative operator.
If the + has heterogeneous operands, there should be a promotion process to the most specific type that generalizes the operand types so that the addition works the same regardless of order, as exists for numeric types. But for general types (and collections particularly) the concept of most specific generalized type including two other collection types is not always sensible, so requiring homogenous operands makes more sense.
With += there is no intended symmetry between operands, the left side is the receiver into which the right side is added.
- speedplane 8y ago> With += there is no intended symmetry between operands, the left side is the receiver into which the right side is added. I'm not sure I buy that, consider a += b versus b += a For integers, the result will be the same, it will just be placed in a different place. For lists, there are differences, but lists are more clearly directional in themselves. For dictionaries, the results can be entirely different.
- zestyping 8y agoI don't find this convincing at all. > so that the addition works the same regardless of order, as exists for numeric types + is not commutative for lists, tuples, or dicts. So the promotion process need not be commutative either. There is no good reason why list + tuple should be forbidden, or dict + items should be forbidden. a [op]= b is commonly and easily explained as "a = a [op] b, where a is mutated in place". Python should not break that explanation with mysterious inconsistencies.
- dragonwriter 8y ago> + is not commutative for lists, tuples, or dicts Yeah, that's a good point. I think I was thinking on the type level rather than the value level, but I am unsure that makes a convincing argument for the behavior here even if it is otherwise true (which I’m not sure it is always, even at the type level.)