Tuples and immutability

Zachary Ware zachary.ware+pylist at gmail.com
Thu Feb 27 11:13:30 EST 2014


On Thu, Feb 27, 2014 at 10:01 AM, Eric Jacoboni <eric.jacoboni at gmail.com> wrote:
> Hi,
>
> I'm using Python 3.3 and i have a problem for which i've still not found
> any reasonable explanation...
>
>>>> a_tuple = ("spam", [10, 30], "eggs")
>>>> a_tuple[1] += [20]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'tuple' object does not support item assignment
>
> Ok... I accept this message as += is a reassignment of a_tuple[1] and a
> tuple is immutable...
>
> But, then, why a_tuple is still modified?
>
>>>> a_tuple
> ('spam', [10, 30, 20], 'eggs')
>
> I get a TypeError for an illegal operation, but this operation is still
> completed?

You're not the first person to have this question :)

http://docs.python.org/3/faq/programming.html#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works

-- 
Zach



More information about the Python-list mailing list