python tuple, can someone explain this behavior?

Viewed 235

I found some questions asking about TypeError: 'tuple' object does not support item assignment on SO, but still, I'm confused about this:

Consider the code snippet:

>>> a = ([],[])
>>> a[0].append(1)       # 1
>>> a
([1], [])
>>> a[0] += [2]

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    a[0] += [2]
TypeError: 'tuple' object does not support item assignment   # 2
>>> a
([1, 2], [])   # 3
>>> 

My questions are:

  1. tuples are immutable, but 1 successfully changed its value.Why?(I know I dont really understand python immutability..)
  2. If 1 is accepted, what's the reason that 2 raise TypeError?
  3. In 3, a gets modified, then what's the point raising a TypeError?

Thank you

1 Answers
Related