"Robert Berman" <berma...@cfl.rr.com> wrote in message
news:1257261606.29483.23.ca...@bermanrl-desktop...
In [69]: l1=[(0,0)] * 4
In [70]: l1
Out[70]: [(0, 0), (0, 0), (0, 0), (0, 0)]
In [71]: l1[2][0]
Out[71]: 0
In [72]: l1[2][0] = 3
---------------------------------------------------------------------------
TypeError Traceback (most recent call
last)
/home/bermanrl/<ipython console> in <module>()
TypeError: 'tuple' object does not support item assignment
First question, is the error referring to the assignment (3) or the
index [2][0]. I think it is the index but if that is the case why does
l1[2][0] produce the value assigned to that location and not the same
error message.
Second question, I do know that l1[2] = 3,1 will work. Does this mean I
must know the value of both items in l1[2] before I change either value.
I guess the correct question is how do I change or set the value of
l1[0][1] when I specifically mean the second item of an element of a 2D
array?
I have read numerous explanations of this problem thanks to Google; but
no real explanation of setting of one element of the pair without
setting the second element of the pair as well.
Tuples are read-only, so you can't change just one element of a tuple:
>>> x=0,0
>>> x
(0, 0)
>>> x[0]=1
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
You can, however, replace the whole thing, as you found:
>>> x=1,1
>>> x
(1, 1)
To do what you want, you a list of lists, not a list of tuples, but there is
a gotcha. This syntax:
>>> L=[[0,0]]*4
>>> L
[[0, 0], [0, 0], [0, 0], [0, 0]]
Produces a list of the *same* list object, so modifying one modifies all:
>>> L[2][0]=1
>>> L
[[1, 0], [1, 0], [1, 0], [1, 0]]
Use a list comprehension to create lists of lists, where each list is a
*new* list:
>>> L = [[0,0] for i in range(4)]
>>> L
[[0, 0], [0, 0], [0, 0], [0, 0]]
>>> L[2][0] = 1
>>> L
[[0, 0], [0, 0], [1, 0], [0, 0]]
-Mark
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor