Why does += of a list within a Python tuple raise TypeError but modify the list anyway? [duplicate]

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[0].extend(['world']);
t[0] = t[0];

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.

Leave a Comment