Search code examples
pythontuples

Why does modifying a list inside a tuple using the "+=" operator in Python result in a changed list, despite tuples being immutable?


We all know that a tuple in Python is an immutable object which means we can’t change the elements once it is created.

my_tuple = ([1],[2],[3])
my_tuple[2] = [3,4,5]

Output:

TypeError: 'tuple' object does not support item assignment

However when I do:

my_tuple[2] += [4,5]:

I get the same error:

TypeError: 'tuple' object does not support item assignment

but the interesting part is when I print the value of my_tuple:

print(my_tuple)

I get:

([1], [2], [3, 4, 5])

so my question is why does modifying a list inside a tuple using the += operator in Python result in a changed list, despite tuples being immutable?


Solution

  • Actually, += operator modifies in-place.

    So, modifying list in-place is good. Then assigns the value back to tuple which is bad (it throws error).

    Since the first operation is successful, it modifies the list then throws error.

    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).

    https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types