Tuples

Xavier Morel xavier.morel at masklinn.net
Thu Dec 15 12:38:07 EST 2005


Tuvas wrote:
> Let's say I make a program something like follows:
> 
> x=[]
> x.append([1,2,3])
> x.append([4,5,6])
> print x
> print x[0]
> print x[0][1]
> x[0][1]=5
> 
> Okay, everything works here as expected except the last line. Why won't
> this work? Thanks for the help!
> 
Works for me, do you have more informations?

 >>> x = list()
 >>> x.append([1,2,3])
 >>> x.append([4,5,6])
 >>> print x
[[1, 2, 3], [4, 5, 6]]
 >>> print x[0]
[1, 2, 3]
 >>> print x[0][1]
2
 >>> x[0][1] = 5
 >>> print x[0][1]
5
 >>>

Now if you're really using tuples, that last line won't work because 
tuples are immutable e.g. you can't modify a tuple's elements after the 
tuple's creation

 >>> y = list()
 >>> y.append((1,2,3))
 >>> y.append((4,5,6))
 >>> print y
[(1, 2, 3), (4, 5, 6)]
 >>> print y[0]
(1, 2, 3)
 >>> print y[0][1]
2
 >>> y[0][1] = 5

Traceback (most recent call last):
   File "<pyshell#16>", line 1, in -toplevel-
     y[0][1] = 5
TypeError: object does not support item assignment
 >>>

And the reason is explicitly stated (tuples don't support item assignment)



More information about the Python-list mailing list