How to best explain a "subtle" difference between Python and Perl ?
Demarche Bruno
demarcheb at gmail.com
Tue Aug 12 15:01:06 EDT 2008
Thank you both for your reply !
On Tue, Aug 12, 2008 at 8:52 PM, Demarche Bruno <demarcheb at gmail.com> wrote:
> Thank you Nigel, it's clearer for both of us now.
> I think wat confused her is the fact that :
>
> L = [1,2,3]
> def foo(my_list):
> my_list.append(4)
>
> will modify L, while the following:
>
> L = [1,2,3]
> def foo(my_list):
> my_list = [1,2,3,4]
>
> will not.
>
> On Tue, Aug 12, 2008 at 6:46 PM, Nigel Rantor <wiggly at wiggly.org> wrote:
>> Palindrom wrote:
>>>
>>> ### Python ###
>>>
>>> liste = [1,2,3]
>>>
>>> def foo( my_list ):
>>> my_list = []
>>
>> The above points the my_list reference at a different object. In this case a
>> newly created list. It does not modify the liste object, it points my_list
>> to a completely different object.
>>
>>> ### Perl ###
>>>
>>> @lst =(1,2,3);
>>> $liste =\@lst;
>>> foo($liste);
>>> print "@lst\n";
>>>
>>> sub foo {
>>> my($my_list)=@_;
>>> @{$my_list}=()
>>> }
>>
>> The above code *de-references* $my_list and assigns an empty list to its
>> referant (@lst).
>>
>> The two code examples are not equivalent.
>>
>> An equivalent perl example would be as follows:
>>
>> ### Perl ###
>>
>> @lst =(1,2,3);
>> $liste =\@lst;
>> foo($liste);
>> print "@lst\n";
>>
>> sub foo {
>> my($my_list)=@_;
>> $my_list = [];
>> }
>>
>> The above code does just what the python code does. It assigns a newly
>> created list object to the $my_list reference. Any changes to this now have
>> no effect on @lst because $my_list no longer points there.
>>
>> n
>>
>
More information about the Python-list
mailing list