Re:Python multi-level break and continue
by IshKebab on Thursday September 08, 2022 @02:31AM
(#32761947)
Nah that's not a good enough example to motivate adding += to Python. You can just do `a.extend(b)`!
Re:Python multi-level break and continue
by eesmith on Thursday September 08, 2022 @04:12AM
(#32762758)
It wasn't meant to be a convincing argument.
It was meant to show your comment at 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.
> 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:
Second, "a += b", which keeps both a and b bound to the same object: