don't understand behaviour of recursive structure

bieffe62 at bieffe62 at
Sat Mar 14 18:05:34 CET 2009

On 14 Mar, 17:31, Dan Davison <davi... at> wrote:
> I'm new to python. Could someone please explain the following behaviour
> of a recursive data structure?
> def new_node(id='', daughters=[]):
>     return dict(id=id, daughters=daughters)

Most probably, here is the problem : try this instead:

def new_node(id='', daughters=None):
     if not daughters: daughters = []
     return dict(id=id, daughters=daughters)

This is one of the less intuitive points in python: default values are
evaluated only once,
at 'compile' time I think. So when you call twice 'new_node' without
specifying the daughters
parameters, both dict will have the _same_  list.  Hence chaos

In other words, it is exactly as if you wrote:

EmptyList = []
def new_node(id='', daughters=EmptyList):
     return dict(id=id, daughters=daughters)

See the problem now? If not try this:

l1 = []
l2 = l1
print l2

See now? The same happens inside your 'nodes'.


More information about the Python-list mailing list