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

Posted on

Question :

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

I just came across something that was quite strange.

>>> t = ([],)
>>> t[0].append('hello')
>>> t
(['hello'],)
>>> t[0] += ['world']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t
(['hello', 'world'],)

Why does it raise TypeError and yet change the list inside the tuple?

Asked By: satran

||

Answer #1:

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.

Answered By: Felix Kling

Answer #2:

This is on http://bugs.python.org/issue11562.

Answered By: Noufal Ibrahim

Leave a Reply

Your email address will not be published.