3 ms·
As an optimisation, you can override += separately from +. A pretty well known oddity related to this is: >>> a = ([0],) # a tuple (immutable) containing a
by masklinn 7y ago
As an optimisation, you can override += separately from +. A pretty well known oddity related to this is:
>>> a = ([0],) # a tuple (immutable) containing a list (mutable)
>>> a[0] = a[0] + [1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a
([0],)
>>> a[0] += [1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a
([0, 1],)
Though to be fair, technically nothing prevents "+" from mutating either operator (it'd just get you tarred and feathered).
- Sohcahtoa82 7y agoWait...did it throw an exception, yet still add the item to the list? EDIT: Tried it myself. Sure enough, it throws the exception, but still adds the item. This seems like a bug. EDIT Part 2: I understand now. `a[0] += [1]` is internally translated to `a[0] = a[0].__iadd__([1])`. The right-hand side is interpreted, mutating a[0] in-place as expected. But then the re-assignment happens, which throws the exception since you're trying to re-assign a value in a tuple, which is immutable.
- masklinn 7y agoYou got it, that’s why it’s so odd.