A question on modification of a list via a function invocation

MRAB python at mrabarnett.plus.com
Mon Aug 14 18:42:55 EDT 2017


On 2017-08-14 20:21, Mok-Kong Shen wrote:
[snip]

> I could more or less understand that in test() alist is interpreted as
> local but in the extended program below in test2() I first write the
> same as in test1(), after which I logically assume that the name alist
> is now known as global and then I write alist=[30,60,90] but that
> doesn't have any effect globally, since I get the output:
> 
> [1, 2, 3]
> [3, 6, 9]
> [3, 6, 9]
> 
> Could you please explain that?
> 
> M. K. Shen
> ---------------------------------------------------------
> 
> def test(alist):
>     alist=[3,6,9]
>     return
> 
> def test1(alist):
>     alist[0],alist[1],alist[2]=3,6,9
>     return
> 
> def test2(alist):

At entry, "alist" is a local name that refers to the list that was 
passed in:

     alist ---> [1,2,3]

Now you change values in that list:

>     alist[0],alist[1],alist[2]=3,6,9

     alist ---> [3,6,9]

You've modified the list that was passed in.

You then bind the local name "alist" to a new list.

>     alist=[30,60,90]

     alist ---> [30,60,90] # This is a new list.

At exit, "alist" refers to a different list from the one that was passed in.

>     return
> 
> ss=[1,2,3]
> test(ss)
> print(ss)
> test1(ss)
> print(ss)
> test2(ss)
> print(ss)
> 



More information about the Python-list mailing list