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?
Tuples are immutable, you may not change their contents.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With