Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puzzling "'tuple' object does not support item assignment" error [duplicate]

Tags:

python

Consider the following:

>>> t = ([],)
>>> t[0].extend([12, 34])
>>> t
([12, 34],)
>>> t[0] += [56, 78]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t
([12, 34, 56, 78],)
>>> 

I understand that tuples are immutable, but the item in the LHS is not a tuple! (The fact that the intended assignment in fact succeeded, the error message notwithstanding, makes the whole scenario only more bizarre.)

Why is this behavior not considered a bug?

like image 553
kjo Avatar asked Jun 21 '13 01:06

kjo


People also ask

How do I update a list inside a tuple?

Tuples are immutable, you may not change their contents.

Can you edit a list in a tuple?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.


1 Answers

t[0] += [56, 78]

is short for

t[0] = t[0].__iadd__([56, 78])

where t is a tuple. The t[0].__iadd__([56, 78]) part changes the list, but then the result cannot be stored as t[0].

The LHS in Python is always a name, never a value. In every Python expression, the RHS is evaluated to a value and assigned to the name on the LHS. In this case the name t[0] cannot be assigned to because t is a tuple.

like image 127
Jochen Ritzel Avatar answered Oct 04 '22 21:10

Jochen Ritzel