2 ms·
https://peps.python.org/pep-0203/ https://peps.python.org/pep-0203/ says: > The idea behind augmented assignment in Python is that it isn’t just an easier way
by eesmith 4y ago
https://peps.python.org/pep-0203/ https://peps.python.org/pep-0203/ says:
> The idea behind augmented assignment in Python is that it isn’t just an easier way to write the common practice of storing the result of a binary operation in its left-hand operand, but also a way for the left-hand operand in question to know that it should operate on itself, rather than creating a modified copy of itself.
Here's an example of how "a += b" is not syntactic sugar for "a = a + b". First, "a = a + b", which rebinds 'a' to a new object while leaving 'b' bound to the original:
>>> a = b = [9,8]
>>> a + b
[9, 8, 9, 8]
>>> a = a + b
>>> a
[9, 8, 9, 8]
>>> b
[9, 8]
Second, "a += b", which keeps both a and b bound to the same object:
>>> a = b = [9,8]
>>> a += b
>>> a
[9, 8, 9, 8]
>>> b
[9, 8, 9, 8]
- IshKebab 4y agoNah that's not a good enough example to motivate adding += to Python. You can just do `a.extend(b)`!
- eesmith 4y agoIt wasn't meant to be a convincing argument. It was meant to show your comment at https://news.ycombinator.com/item?id=32741165 https://news.ycombinator.com/item?id=32741165 wasn't a relevant parallel, because it ignored how "a+=1" and "a=a+1" are different. For a more convincing use, consider NumPy arrays, where a+=1 re-use the same (potentially very large) array, while a=a+1 creates a new array. import numpy a = b = numpy.array([[1,2], [3, 9]]) a += 1 # modify in-place a = a + 1 # create a new array >>> a array([[ 3, 4], [ 5, 11]]) >>> b array([[ 2, 3], [ 4, 10]]) In-place modification can improve performance over using intermediate/temporary arrays.