On 08/14/2017 01:02 PM, Mok-Kong Shen wrote:
Am 14.08.2017 um 21:53 schrieb Ned Batchelder:
[snip]

def test(alist):
   alist=[3,6,9]
   return

def test1(alist):
   alist[0],alist[1],alist[2]=3,6,9
   return

def test2(alist):
   alist[0],alist[1],alist[2]=3,6,9
   alist=[30,60,90]
   return

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

Your test2 function first mutates the caller's list by assigning
alist[0]=3, then it rebinds the local name alist to be a new list.  So
the caller's list is now [3, 6, 9].

Sorry for my poor knowledge. After the line alist[0]..., what is the
status of the name alist? It's now a global name, right? So why in the
line following that the name alist would suddenly be interpreted as
local? I can't yet fully comprehend the logic behind that.

M. K. Shen
Here is my attempt to clarify the situation with some ascii graphics.
(Well, not ascii, but utf-8 box-drawing characters — I hope they come through 
ok.
And, of curse, it won't display properly with a proportional font.)

The left side is the program lines, and the right side tries to show the way Python implements the name binding to the data in memory. (But I abbreviated the long assignment line,
alist[0],alist[1],alist[2]=3,6,9 to <assignment>)

Program line          Variable bound to memory

===========  Initial assignment  ============

ss = [1, 2, 3]              ss ───> [1, 2, 3]

===============  test() code  ===============

def test(alist):            ss ─┬─> [1, 2, 3]
                         alist ─┘
---------------------------------------------
    alist = [3, 6, 9]       ss ───> [1, 2, 3]
                         alist ───> [3, 6, 9]
---------------------------------------------
    return                  ss ───> [1, 2, 3]
                         alist <Garbage collected>

===============  test1() code  ==============
def test1(alist):           ss ─┬─> [1, 2, 3]
                         alist ─┘
---------------------------------------------
    <assignment>            ss ─┬─> [3, 6, 9]
                         alist ─┘
---------------------------------------------
    return                  ss ───> [3, 6, 9]
                         alist <Garbage collected>

===============  test2() code  ==============
def test2(alist):           ss ─┬─> [1, 2, 3]
                         alist ─┘
---------------------------------------------
    <assignment>           ss ─┬─> [3, 6, 9]
                        alist ─┘
---------------------------------------------
    alist = [30, 60, 90]    ss ───> [3, 6, 9]
                         alist ───> [30, 60, 90]
---------------------------------------------
    return                  ss ───> [3, 6, 9]
                         alist <Garbage collected>

--
     -=- Larry -=-
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to