Behavior of default parameter in a function

2010-03-11 Thread jitendra gupta
def foo(x = [0]): x[0] = x[0] + 1 return x[0] def soo(x = None): if x is None: x = [0] x[0] = x[0] + 1 return x[0] foo() 1 foo() #See the behavior incremented by one 2 foo([1]) # but here based on given number 2 foo() 3 foo([1]) 2 foo() 4 soo() 1 soo() 1 soo([1]) 2 soo() 1 Why foo() is

Re: Behavior of default parameter in a function

2010-03-11 Thread Shashank Singh
quoting from docs:http://docs.python.org/reference/compound_stmts.html *Default parameter values are evaluated when the function definition is executed.* This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call.

Re: Behavior of default parameter in a function

2010-03-11 Thread Gary Herron
This is addressed in the FAQ. http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects jitendra gupta wrote: def foo(x = [0]): x[0] = x[0] + 1 return x[0] def soo(x = None): if x is None: x = [0] x[0] = x[0] + 1 return x[0] foo() 1 foo() #See the behavior