arguments for subsequent call of function in python -


this question has answer here:

hi new python. can explain how below 2 pieces of code give different outputs? function gets defined each time called?

 def f(a, l=[]):       l.append(a)       return l    def f(a, l=none):      if l none:          l = []      l.append(a)      return l 

on running

 print f(1)  print f(2)  print f(3) 

i these outputs respectively

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

this common 'gotcha' new python developers. in first example looks new empty list should created each time function called without second parameter. isn't. single list created when function object created, when python script loaded or finish entering function in interactive shell. list used every invocation of function, hence acculumation see.

the second standard way of working round this, , creates new list instance each time function called without second parameter.

under covers python putting default values finds in function definition property of function called defaults. can see how same instance present between calls in interactive shell:

>>> def f(a,b=[]): ...     b.append(a) >>> f.__defaults__ ([],) >>> f(1) >>> f.__defaults__ ([1],) >>> f(2) >>> f.__defaults__ ([1,2],) 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -