Recursive function returning a list

Steve Holden steve at holdenweb.com
Mon Jul 17 13:43:34 EDT 2006


Fabian Steiner wrote:
> Hello!
> 
> I have got a Python "Device" Object which has got a attribute (list) 
> called children which my contain several other "Device" objects. I 
> implemented it this way in order to achieve a kind of parent/child 
> relationship.
> 
> Now I would like to get all children of a given "Device" object and 
> thought that it would be the best way to use recursive function.
> 
> This is what I got so far:
> 
>      def getAllChildren(self, children=[]):
>          if self.children:
>              children.extend(self.children)
>              for child in self.children:
>                  child.getAllChildren(children)
>          return children
> 
> Unfortunately, it doesn't work like expected since the default parameter 
> children=[] is evaluated only once. That's why the children list becomes 
> larger and larger after calling the method several times but I can't 
> think of another possibility.
> 
> Do you have any ideas?

This is a standard question, and has a standard answer: replace

       def getAllChildren(self, children=[]):

with

       def getAllChildren(self, children=None):
           if children is None:
               children = []

That way a new empty list is created for each call that receives no 
"children" argument. Otherwise the same (once-empty) list is used for 
them all.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list