don't understand behaviour of recursive structure

Dan Davison davison at stats.ox.ac.uk
Sat Mar 14 15:53:23 EDT 2009


bieffe62 at gmail.com writes:

> 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:

Yes, that's very clear. Thanks for all the answers on this thread.
Dan

>
> l1 = []
> l2 = l1
> l1.append(1)
> print l2
>
> See now? The same happens inside your 'nodes'.
>
>
> Ciao
> ----
> FB
> --
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list