Default function arguments behaving badly

rafi rafi at free.fr
Wed Aug 24 11:50:42 EDT 2005


jonny.longrigg at gmail.com wrote:
> Hi

hi

> I'm having some trouble with a function I've written in Python:
> 
> def myFunction(l1,l2,result=[]):
>     index=0
>     for i in l1:
>         result.append([])
>         if type(i)==list:
>             myFunction(i,l2,result[index])
>         else:
>             for j in l2:
>                 result[index].append(i*j)
>         index+=1
>     return result

> The problem is that it works if I run it once, but then on repeated
> runs the value for 'result' doesn't seem to set itself to my default of
> [], but instead uses the state it was in last time the function was
> run.

> Does anyone know what is going on here? Is there an easy solution?

the list you provide as default parameter is evaluated once (at loading 
time of the function). so each time you call the function, it uses the 
same list that has been filled before... you do not have the problem 
with say and int or a string as they are non mutable objects. however 
lists are mutable objects so... modify your function as follow:

def myFunction(l1,l2,result=None):
     if result is None:
         result = []

hth

-- 
rafi

	"Imagination is more important than knowledge."
	                            (Albert Einstein)



More information about the Python-list mailing list