I just came across something that was quite strange.
0].append('hello') t (['hello'],) t += ['world'] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment t (['hello', 'world'],)t = (,) t[
Why does it raise
TypeError and yet change the
list inside the
As I started mentioning in comment,
+= actually modifies the list in-place and then tries to assign the result to the first position in the tuple. From the data model documentation:
These methods are called to implement the augmented arithmetic assignments (+=, -=, =, /=, //=, %=, *=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).
+= is therefore equivalent to:
t.extend(['world']); t = t;
So modifying the list in-place is not problem (1. step), since lists are mutable, but assigning the result back to the tuple is not valid (2. step), and that’s where the error is thrown.
This is on http://bugs.python.org/issue11562.