[Tutor] Need some help

Steven D'Aprano steve at pearwood.info
Sat May 7 10:08:31 CEST 2011


Aaron Brown wrote:
> Here is the code I have, and the error.I don't understand the TUPLE problem.
> Can someone explain.


The error you get is:

TypeError: 'tuple' object does not support item assignment


This tells you that tuples are immutable (fixed) objects. You cannot do 
this:


 >>> t = (1, 2, 3)
 >>> t[1] = 42  # Change the item in place.
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment


Instead, you can recreate the tuple as needed, using slicing:

 >>> t = (1, 2, 3)
 >>> t = t[0:1] + (42,) + t[2:]  # note the comma in the middle term
 >>> t
(1, 42, 3)


or you can use lists instead:

 >>> t = [1, 2, 3]
 >>> t[1] = 42
 >>> t
[1, 42, 3]



-- 
Steven



More information about the Tutor mailing list