Unexpected behavior of list of list

kghose kaushik.ghose at gmail.com
Fri Mar 9 20:41:56 EST 2007


On Mar 9, 8:30 pm, "kghose" <kaushik.gh... at gmail.com> wrote:
> 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

OK, I looked at the previous few threads and I think I understand why.
I refered to this page http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list

thanks
-kaushik




More information about the Python-list mailing list