The value of the empty list in the function parameter, an example here

Possible duplicate:
"Least Surprise" in Python: argument argument resolved by argument

def f(a, L=[]): L.append(a) return L print(f(1, [1, 2])) print(f(1)) print(f(2)) print(f(3)) 

It is interesting why the other f (1), f (2), f (3) did not join the first f (1, [1,2]). I think the result should be:

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

But that is not the result. I do not know why.

+7
source share
2 answers

There are two different problems (better called concepts) combined into a single task statement.

The first is related to the SO question, as pointed out by agh. The thread gives a detailed explanation, and there is no point in explaining it again, except for this thread. I can simply take advantage of the privilege of saying that functions are first class objects, and the parameters and their default values ​​are limited during declaration. Thus, the parameters act as static parameters of the function (if something can be made possible in other languages ​​that do not support objects of the first class class.

The second problem is to which list object the parameter L bound. When you pass the parameter, the List parameter passed is what L. is bound to. When called without any parameters, it is more like connecting to another list (the one that is referred to as the default parameter), which will differ from the course what was transmitted on the first call. To make this case more visible, simply change your function as follows and run the samples.

 >>> def f(a, L=[]): L.append(a) print id(L) return L >>> print(f(1, [1, 2])) 56512064 [1, 2, 1] >>> print(f(1)) 51251080 [1] >>> print(f(2)) 51251080 [1, 2] >>> print(f(3)) 51251080 [1, 2, 3] >>> 

As you can see, the first call prints a different parameter identifier L , contrasting with subsequent calls. Therefore, if the lists are different from each other, this will be the behavior and value that is added. Hope this should make sense now

+6
source

Why do you expect the results if you call the function, where to initialize the empty list, if you do not pass the second argument?

For the results you want, you should use closure or global var.

0
source

All Articles