Recursive function returning a list

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Mon Jul 17 13:47:21 EDT 2006


In <e9gdpa$lhb$01$1 at news.t-online.com>, Fabian Steiner wrote:

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

    def get_all_children(self, accumulator=None):
        if accumulator is None:
            accumulator = list()
        accumulator.extend(self.children)
        for child in self.children:
            child.get_all_children(accumulator)
        return accumulator

Ciao,
	Marc 'BlackJack' Rintsch




More information about the Python-list mailing list