[Tutor] altering a list of lists

Alan Gauld alan.gauld at btinternet.com
Mon Nov 26 01:29:59 CET 2007


"Christina Margaret Berens" <bere6944 at blue.unco.edu> wrote

> or gold on the board, I have to change one of the spaces to a '+', 
> but
> when I do it, it changes all the elements in that position in each
> list.

This is a classic sign that you have 5reated your nested list
by using the same list instead of copying it...


> # set up of board
> Board = 
> [['- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> -']]
> width = ['|']
> for i in range(30):
>    for j in range(1):
>        width.append('  ')
> width.append('|')
>
> for i in range(30):
>    Board.append(width)

And here it is, you just assin the same sublist for eah row,
you need to create a new copy for each one.

We can do that with slicing, thus:

    Board.append(width[:])

Which should fix the problem.


-- 
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