python- function - list - references

Today interview encountered a problem

def func(a,l=[]):

  l.append(a)

  return l

func('a')

func('abc',[1,2,3,4])

func(10)

['a']

[1,2,3,4,'abc']

['a',10]

But if you continue with the next func () function list of contents inside the container has been changing, it's just not the case assignment, if an assignment it?

From the following code found in the preparation of the code, pay attention to function and reference issues. Because there is a defined list of container in a function, and it is created when the function definition. Because the function returns a list of references of the container, so the results of the back of the impact on the front. Popular speak, at the same time that the two variables referenced address of the container. Within the address data changes on the two variables are affected, it can be said shallow copy.

In [17]: def func(a,l=[]):
    ...:     l.append(a)
    ...:     return l
    ...: 
    ...: 

In [18]: l1 = func('a')

In [19]: l2 = func('abc',[1,2,3,4])

In [20]: l3 = func(10)

In [21]: print(l1,l2,l3)
['a', 10] [1, 2, 3, 4, 'abc'] ['a', 10]

Guess you like

Origin www.cnblogs.com/deepstack/p/10950558.html