A question on modification of a list via a function invocation

Chris Angelico rosuav at gmail.com
Wed Aug 16 20:35:19 EDT 2017


On Thu, Aug 17, 2017 at 9:03 AM, Mok-Kong Shen
<mok-kong.shen at t-online.de> wrote:
> Am 17.08.2017 um 00:39 schrieb Chris Angelico:
>>
>> On Thu, Aug 17, 2017 at 8:29 AM, Mok-Kong Shen
>> <mok-kong.shen at t-online.de> wrote:
>>>
>>> I have earlier learned some other (older) programming languages. For
>>> these the formal parameters are either "by reference" or "by value".
>>> In the first case, any modification of the formal parameter inside
>>> a function affects the corresponding actual parameter of a function
>>> call, while in the second case a copy of the actual parameter is
>>> passed into the function so that any modification of the formal
>>> parameter inside the function has no effect at all outside. This is
>>> extremely clear-cut in comparison to Python, isn't it? Anyway, while
>>> any new user of a programming language certainly can be expected to
>>> take good efforts to learn a lot of new stuffs, I suppose it's good
>>> for any practical programming language to minimize the cases of
>>> surprises for those that come from other programming languages.
>>
>>
>> Python has a data model that is neither of the above, but it's simpler
>> in that you have one pattern for everything. Whether you're looking at
>> function parameters, return values, assignment, loops, function
>> definitions, or anything else, the model is exactly the same. And that
>> model is: objects exist independently of names, and names refer to
>> objects. If you do "x = y", you're saying "figure out which object 'y'
>> means, and make the name 'x' refer to it". If you do "x[1] = y",
>> you're saying "figure out which object 'y' means, and tell the object
>> that 'x' means that it should make [1] refer to that object". So if
>> you have multiple names referring to the same object, any change you
>> ask that object to do will be seen by every other name that also
>> refers to it - because it's all about the object.
>
>
> I may have misunderstood you. But I don't think what you wrote
> above would explain why the program below produces the output:
>
> [1, 2, 3]
> [3, 6, 9]
>
> M. K. Shen
> -----------------------------------------------------
>
> def test2(alist):
>   alist[0],alist[1],alist[2]=3,6,9
>   alist=[30,60,90]
>   return
>
> def test3(alist):
>   alist=[30,60,90]
>   alist[0],alist[1],alist[2]=3,6,9
>   return
>
> ss=[1,2,3]
> test3(ss)
> print(ss)
> test2(ss)
> print(ss)

It does. Go through it step by step. Think about objects and names,
not about variables. Also, please keep things on the list - thanks! :)

ChrisA



More information about the Python-list mailing list