Recursive functions

D-Man dsh8290 at rit.edu
Thu Jun 28 14:29:38 EDT 2001


On Thu, Jun 28, 2001 at 04:28:28PM +1000, Tom Harris wrote:
| Hi,
| 
| I am very new to Python, and I am trying to get a recursive function
| working. The problem is that the function modifies one of its arguments,
| which is not a local copy of a variable (local to this stack frame of the
| function, like in call by value in C) but a reference to a variable owned by
| the function namespace, so changes to the variable are inherited by other
| calls to the same function. I tried copying the argument to a variable in
| the function body, but of course this suffers from the same problem.

This is the same as in C -- the argument 'aList' would be of type
GList* (if you use glib).

| This is the idea, but the list just keeps on growing.
| 
| def f(aList):
| 	...
| 	aList.append(stuff)
| 	f(aList)
| 
| What is the solution? 

This depends on what you are doing in '...'.  Maybe

def f( aList ) :
    ...
    f( aList + stuff )

would help.  The add operator on a list creates a shallow copy of the
list with the 'stuff' at the end of it.  It is similar to doing

    tmp = aList[:]
    tmp.append( stuff )
    f( tmp )

HTH,
-D





More information about the Python-list mailing list