don't understand behaviour of recursive structure

bieffe62 at gmail.com bieffe62 at gmail.com
Sat Mar 14 13:05:34 EDT 2009


On 14 Mar, 17:31, Dan Davison <davi... at stats.ox.ac.uk> 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
l1.append(1)
print l2

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


Ciao
----
FB



More information about the Python-list mailing list