Unexpected behavior of list of list

kghose kaushik.ghose at gmail.com
Fri Mar 9 20:30:09 EST 2007


Hi,

The following code

listoflists = [[]]*2
listoflists[0].append(1)

appends(1) to both listoflists[0] and listoflists[1] (which I did not
expect)

while

listoflists = [[]]*2
listoflists[0] = [1]
listoflists[0].append(2)

works as expected.i.e. only listoflists[0] gets 2 appended to it and
any further operations work as expected.

I can't figure out why. Any help with explaining this would be much
appreciated

thanks!
-Kaushik




More information about the Python-list mailing list