简体   繁体   中英

Why does line 1 print [1,2,3,“a”], and not just [1,2,3]? is it because of the L2=f2(L1,'a')? HOW?

def f1(v,y):
      v = 4
      y += v
      return y

def f2(L,x):
    L.append(x)
    return L
L1 = [1,2,3]
L2 = `f2(L1,'a')`
print(L1)    # Line 1
print(L2)    # Line 2
a = 2
b = 3
c = f1(a,b)
print(a)     # Line 3
print(c)     # Line 4
print( f1(L1,1) )  # Line 5

Why does line 1 print [1,2,3,"a"], and not just [1,2,3]? Is it because of the L2=f2(L1,'a')? HOW?

f2 appends the second argument to the list passed as the first argument. Appending "a" to [1, 2, 3] will produce the output of [1, 2, 3, "a"] you're seeing.

That is because, while passing the argument L1 to function f2 , pointer of a variable is passed. Therefore, when you append a value to variable L inside your function, the list L1 is also modified( L is nothing but a pointer to L1 )

if a function modifies an object passed as an argument, the caller will see the change

Take a look at this

Therefore is it beacuse of the L2=f2(L1,'a')? yes

Hope it helps!

If want to get L1 as [1,2,3] then assign it to new list...

def f2(L,x):
    L3 = L.copy()  # copy passed list 'L' to L3
    L3.append(x)
    return L3 # return list with x at end of list

But this won't change your current list L1

Let L = [1,2,3].
you want to append 'a' in this list
like this,L.append('a')
then list will be L = [1,2,3,'a']. R8?
Same thing happen here using a function f2(L,'a')
f2 function takes a list and a value 'a' as a parameter and append 'a' into L list then return L with value [1,2,3,'a'].
and this list is assigned to a variable called L2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM