initialized list: strange behavior
Arnaud Delobelle
arnodel at googlemail.com
Tue Nov 25 09:23:00 EST 2008
Jason Scheirer <jason.scheirer at gmail.com> writes:
> 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.
There's no need to introduce references: you're creating a list with the
same object at each position.
[...]
> Python is pass-by-reference, not pass-by-value.
It's certainly not pass-by-reference, nor is it pass-by-value IMHO.
--
Arnaud
More information about the Python-list
mailing list