list as paremeters...

Ulrich Petri ulope at gmx.de
Sun Aug 31 13:24:12 CEST 2003


"shagshag13" <shagshag13 at yahooPLUSDESPAM.fr> schrieb im Newsbeitrag
news:3f51ce6e$0$26843$626a54ce at news.free.fr...
> hello,
>
> i have an unexpected behaviour that i didn't understand, can someone
explain
> this to me ?
>
> >>> def doit(s, stack = []):
>  if s == '':
>   return stack
>
>  stack.append(s[:1])
>  return doit(s[1:], stack)
>
> >>> doit('this')
> ['t', 'h', 'i', 's']
> >>> doit('this')
> ['t', 'h', 'i', 's', 't', 'h', 'i', 's']
> >>> doit('this')
> ['t', 'h', 'i', 's', 't', 'h', 'i', 's', 't', 'h', 'i', 's']
>
> and so on ... i would expect it to stuck to
> >>> doit('this')
> ['t', 'h', 'i', 's']
>
> why does this 'stack' remind of previous call ?
>

Try this:
>>>
def doit(s, stack=None):
    if stack == None:
        stack=[]
    if s == '':
        return stack

    stack.append(s[:1])
    return doit(s[1:], stack)

The problem is the default value auf stack.

IIRC Default values are not created each time the function called but rather
only the first time (am i correct here?). And since a list is mutable it
"rememberes" the previous value.

Ciao Ulrich






More information about the Python-list mailing list