Python: list operation when the list is an element in a tuple

I am using Python2.7. * and try to check the operation of the list when list is a tuple element.
but I found something that I cannot 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 the tuple is immutable and the list is changed, and I know that it is list +=equivalent list.extend()from List + = Tuple vs List = List + Tuple .
But now I'm in the sea to explain the code above.

+4
source share
1 answer

In this code, you assign the first element, which is not possible in the tuple.

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

a[0]+[1,2,3], a[0], .

.

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

, , . , :

x , .

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

, id [], x x+[1] , x 1 . , a[0] = a[0] + [1,2,3] , .

, id:

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

, y . , . , , , .

: , , .

+7

All Articles