1

Hi I am new to python. Can someone explain how the below two pieces of code give different outputs? Does the function gets defined each time it is called?

 def f(a, L=[]): 
     L.append(a) 
     return L



def f(a, L=None):
     if L is None:
         L = []
     L.append(a)
     return L

on running

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

I get these outputs respectively

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



 [1]
 [2]
 [3]
user732362
  • 395
  • 4
  • 10
  • 19

3 Answers3

2

This is a very common 'gotcha' for new python developers. In the first example it looks like a new empty list should be created each time the function is called without the second parameter. It isn't. A single list is created when the function object is created, which is basically when the python script is loaded or you finish entering the function in the interactive shell. This list is then used for every invocation of the function, hence the acculumation you see.

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

Under the covers Python is putting any default values it finds in the function definition into a property of the function called defaults. You can see how the same instance is present between calls in the interactive shell:

>>> def f(a,b=[]):
...     b.append(a)
>>> f.__defaults__
([],)
>>> f(1)
>>> f.__defaults__
([1],)
>>> f(2)
>>> f.__defaults__
([1,2],)
Steve Allison
  • 1,091
  • 6
  • 6
0

Default arguments in python are evaluated at the function declaration point - when it's first seen by the interpreter.

In your first snippet, the L argument is "given" a list as the default, and so the values are appended.

In the second snippet, L is always None on entry into the function, so gets re-created each time.

SteveLove
  • 3,137
  • 15
  • 17
0

The function default parameters are evaluated when the function is defined. In your case def f(a, L=[]):creates an empty list that is then passed every time the function is called without the L parameter. So every call to the function operates on the same list, that's why it gives different output each time.

In your second function an empty list is created every time the function is called, so it works as expected.

Esenti
  • 707
  • 6
  • 12