Python: list operation when list is an element in tuple

list, python-2.7

Solution

In this code you are assigning to the first element, which is not possible in a tuple.

>>> a = ([],)
>>> a[0] = a[0] + [1,2,3] 

Here, on the right hand side you are creating a new list from `a[0]+[1,2,3]` and then attempting to assign it back into `a[0]` which isn't legal.

In this code you are retrieving the first element of a tuple and then operating on that.

>>> c = ([], )
>>> c[0].extend([1,2,3])

Granted, its a small semantic difference, but it is that in the first you are attempting to reassign an element in a tuple. But lets look a little at whats happening behind the scenes:

Here we assign a list into `x` and observe how its id changes through different operations.

>>> x=[]
>>> id(x)
139987361764560
>>> id([])
139987361677112
>>> id(x+[1])
139987361829736
>>> x.append(1)
>>> x
[1]
>>> id(x)
139987361764560

Note that the id for `[]`, `x` and `x+[1]` are all different, but the id for `x` after we append a `1` is still the same. This reenforces the statement above that says that the statement `a[0] = a[0] + [1,2,3]` is creating a new list and then trying to assign it into the tuple.

But what of our tuple, well lets do some id checking again:

>>> id(y)
139987361830168
>>> id(y[0])
139987361677112
>>> id(y[1])
139987361723384
>>> y[1] = y[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> y[1].append(1)
>>> id(y[1])
139987361723384
>>> y
([], [1])

Again, we create a tuple, and can see that the tuple `y` and each of its elements have different ids. But note, we can't even assign the same list back into the same spot in the tuple. However, we can perform operations on that list as expected and see that the tuple changes.

Regarding immutability: The important thing to note here is that the tuple doesn't change, because the ids of the objects within the tuple don't change.

Problem

I am using Python2.7.*, and trying a test of list operation when list is the element of a tuple. but I found something I can not get myself understand: ``` >>> a = ([],) >>> a[0] = a[0] + [1,2,3] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> a ([],) >>> b = ([], ) >>> b[0] += [1,2,3] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> b ([1, 2, 3],) >>> c = ([], ) >>> c[0].extend([1,2,3]) >>> >>> c ([1, 2, 3],) ``` I know that tuple is immutable and list is mutable, and I know that `list +=` is equivalent to `list.extend()` from List += Tuple vs List = List + Tuple. But now I am at sea that how to explain the code above.

Original source

Related problems