[Tutor] List indexing problem

Alan Gauld alan.gauld at btinternet.com
Sat Jul 26 01:15:12 CEST 2008


"Mike Meisner" <mikem at blazenetme.net> wrote

def testanalysis():
    IP = []
    temp = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]
    # initialize to zero
    for i in range(20):
        IP.append(temp)

this appends the same list (temp)  20 times. So when you 
change the list it is reflected 20 times. Lists hold references 
to their data (even if the data is anotyher list). You need to 
make copies before appending.

Don't worry, this is one of the most common gotchas in 
Python...

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