4 ms·
It's a design decision to allow it to behave differently, as you can implement += with a more efficient in-place version, instead of a copying one where the lva
by maweki 6y ago
It's a design decision to allow it to behave differently, as you can implement += with a more efficient in-place version, instead of a copying one where the lvalue might be different/new and you have to keep the old a.
I even think this is good design, as by convention + does not mutate its arguments but += can be a fast mutating version.
- pansa2 6y agoI guess reference counting makes copying a list in Python a much more expensive operation than it would be in other languages. Although perhaps it could also be used to avoid copying in cases where the list's own reference count is exactly 1? Anyway, there's nothing wrong with offering an operator to change a list in-place, but IMO `+=` is the wrong way to spell it.
- maweki 6y ago> but IMO `+=` is the wrong way to spell it. Again, operator overloading. __iadd__ just calls append. Many a library might do something much better. But as it looks like the in-place version of +, even for lists it seems fine (although I've been missing a concat-operator in python for years - seems we're stuck with +).
- yongjik 6y agoI'd say it's even deeper - the += operator is fundamentally tied with Python's semantics. Consider: >>> a = [1, 2] >>> b = a >>> a = a + [3] >>> b [1, 2] It has to be [1, 2] because the third line creates a new object. If a + operation changes its operand, then the concept of object identity breaks down - at least, it will be a very different language.
- pansa2 6y agoYou’re right - I’m not suggesting that `+` should work in-place, but that `a += b` should do the same thing as `a = a + b` and not work in-place.
- BerislavLopac 6y agoSo you're saying that a += b should create a new object and assign it to a? Now that would be even more unexpected...
- pansa2 6y agoI don’t think it’s unexpected for an augmented assignment operator to do an assignment. It is unexpected for it to instead call `extend`. It’s even worse to do the first for some types and the second for other types.