A question on modification of a list via a function invocation

Ned Batchelder ned at nedbatchelder.com
Mon Aug 14 14:50:51 EDT 2017


On 8/14/17 2:21 PM, Mok-Kong Shen wrote:
> I ran the attached program and got the following output:
>
> [1, 2, 3]
> [3, 6, 9]
>
> I don't understand why the modification doesn't work in the case of
> test() but does work in the case of test1().
>
> Thanks for your help in advance.
>
> M. K. Shen
>
> ------------------------------------------------------------
>
> def test(alist):
>   alist=[3,6,9]
>   return
>
> def test1(alist):
>   alist[0],alist[1],alist[2]=3,6,9
>   return
>
> ss=[1,2,3]
> test(ss)
> print(ss)
> test1(ss)
> print(ss)

This reassigns the name alist:  alist = [3, 6, 9].   That changes the
local variable, but cannot affect the caller's variables.

This leaves alist as the same object, but reassigns its elements,
mutating the list:  alist[0] = 3

This talk has more details: https://nedbatchelder.com/text/names1.html

--Ned.



More information about the Python-list mailing list