[Tutor] List of lists help

Alan Gauld alan.gauld at btinternet.com
Thu Nov 20 10:03:07 CET 2008


<btkuhn at email.unc.edu> wrote

>
> self.boardarray[row][col] = self.currentPlayer
>
> 4, self.boardarray[2][4] will be set to "2". Instead, the program is 
> setting multiple values within the list as 2. Here is an example 
> output, when I click on (0,0):
>
> [[2, 0, 0, 0, 0], [2, 0, 0, 0, 0], [2, 0, 0, 0, 0], etc.

This is almost always caused by you initialising the data wrongly.
You have set every item in your list to point to the same sublist.
Something like

>>> L = [[0,0,0] *3]

Now L contains 3 copies of the same list so when you change
any one copy it is reflected in all of the other copies.

>>> L[0][1] = 6
>>> L
[[0,6,0],[0,6,0],[0,6,0]]

You can avoid this by constricting the list using a list comprehension
(or any of several other solutions)

L = [[0,0,0] for n in range(3)]
L[0][1] = 7
L
[[0, 7, 0], [0, 0, 0], [0, 0, 0]]

Remember that Python does everything by references so

a = foo
b = foo

leaves a and b pointing at the same foo object not two
copies of foo. The same applies to lists. If you want a
copy you need to explicitly make a copy.

L1 = [1,2]
L2 = L1[:]

Now L1 and L2 are two separate lists.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list