list as paremeters...

Caleb Land bokonon at rochester.rr.com
Sun Aug 31 16:05:14 EDT 2003


"shagshag13" <shagshag13 at yahooPLUSDESPAM.fr> wrote in message 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 ?

The problem is your function declaration:
    def doit(s, stack = []):

That empty list is evaluated only once, so each call to doit without a
stack argument uses the same list.

You should change that to:

def doit(s, stack=None):
    if s == '':
        return stack

    if stack is None:
        stack = []    # A new empty list is created each time

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

-Caleb Land




More information about the Python-list mailing list