Antoon Pardon wrote: >> The left one is equivalent to: >> >> __anon = [] >> def Foo(l): >> ... >> >> Foo(__anon) >> Foo(__anon) > > So, why shouldn't: > > res = [] > for i in range(10): > res.append(i*i) > > be equivallent to: > > __anon = list() > ... > > res = __anon > for i in range(10): > res.append(i*i)
Because the empty list expression '[]' is evaluated when the expression containing it is executed. > >> The left has one list created outside the body of the function, the >> right one has two lists created outside the body of the function. Why >> on earth should these be the same? > > Why on earth should it be the same list, when a function is called > and is provided with a list as a default argument? Because the empty list expression '[]' is evaluated when the expression containing it is executed. > > I see no reason why your and my question should be answered > differently. We are agreed on that, the answers should be the same, and indeed they are. In each case the list is created when the expression (an assigment or a function definition) is executed. The behaviour, as it currently is, is entirely self-consistent. I think perhaps you are confusing the execution of the function body with the execution of the function definition. They are quite distinct: the function definition evaluates any default arguments and creates a new function object binding the code with the default arguments and any scoped variables the function may have. If the system tried to delay the evaluation until the function was called you would get surprising results as variables referenced in the default argument expressions could have changed their values. -- http://mail.python.org/mailman/listinfo/python-list