What happens to a list when passing a function?

I am trying to understand how a list is processed when passed as an argument to a function. So, I did the following:

I initialized the list:

ll = [1,2,3,4] 

and define the function:

def Foo(ar):
    ar += [11]

I passed a list of functions:

Foo(ll)

and when I print it, I got:

print ll # [1, 2, 3, 4, 11] #case(1)

So far so good.

Now I have changed the function to reset the list so that it has only one element:

def Foo(ar):
    ar = [11]

I remembered the syntax:

Foo(ll)

and when I reprinted it, he led to the same list:

print ll # [1, 2, 3, 4] # case(2)

I thought the list was passed as a link; therefore, everything we do with the list inside the function will always change the original function passed from the main program. Therefore, for case (2), I expected the following result:

print ll # [11] # case(2) expected result

Did I miss something?

+4
source share
3 answers

ar += [11] . ( : __iadd__). Python , , ar. __iadd__ list list.

ar = [11] , , ar. ar ll .

, - :

ar[:] = [11]
+7

. Python , , .

- . , Python , , .

, , :

def Foo1(ar):
    ar += [11]

, ar, , .

:

def Foo2(ar):
    ar = [11]

, ar, ar . fogotten, .

, :

a = [1,2,3]

:

Foo1(a)

, , :

Foo2(a)

a.

, ,

def Foo3(a):
    a[:] = [11]

a, , .

, :

a = []
b = []
c = a
a.append(1)
b.append(2)
c.append(3)
print a
print b
print c

:

[1, 3]
[2]
[1, 3]

, ?

+5

, +=, , =. , :

ar = [11]

ar. , ar, , , print ll , .

ar += [11]

ar = ar + [11]

ar = ar + [11], ll . , += , , , , ar, , , . , , 11, ll.

+2

All Articles