initialized list: strange behavior
Gary Herron
gherron at islandtraining.com
Tue Nov 25 07:48:44 CET 2008
alexander.genkin at gmail.com wrote:
> Hi Python experts! Please explain this behavior:
>
[] make an empty list.
[ [],[],[] ] makes a list of three different empty lists.
3*[[]] makes a list of three references to the same list.
Realy, that should explain it all, but perhaps there are enough empty
lists here to obscure things. Try this:
Here b is a list that contains three references to a. Modify a, and
all three references to a show the modification:
>>> a = [1,2,3]
>>> b = [a,a,a]
>>> a.append(4)
>>> b
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
Gary Herron
>
>>>> nn=3*[[]]
>>>> nn
>>>>
> [[], [], []]
>
>>>> mm=[[],[],[]]
>>>> mm
>>>>
> [[], [], []]
>
> Up till now, 'mm' and 'nn' look the same, right? Nope!
>
>
>>>> mm[1].append(17)
>>>> mm
>>>>
> [[], [17], []]
>
>>>> nn[1].append(17)
>>>> nn
>>>>
> [[17], [17], [17]]
>
> ???
>
> Python 2.5 Win XP
>
> Thanks!
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list