initialized list: strange behavior

Jason Scheirer jason.scheirer at gmail.com
Tue Nov 25 01:46:47 EST 2008


On Nov 24, 10:34 pm, alexander.gen... at gmail.com wrote:
> Hi Python experts! Please explain this behavior:
>
> >>> 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!

You're creating three references to the same list with the
multiplication operator. You can easily get the same behavior because
of similar mechanics in a more common scenario:

In [1]: a = []

In [2]: b = a

In [3]: a, b
Out[3]: ([], [])

In [4]: a.append(1000000)

In [5]: a, b
Out[5]: ([1000000], [1000000])

Python is pass-by-reference, not pass-by-value.



More information about the Python-list mailing list