|
Caleb Land |
at Aug 31, 2003 at 8:05 pm
|
⇧ |
| |
"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 ?
if s == '':
return stack
stack.append(s[:1])
return doit(s[1:], stack)
['t', 'h', 'i', 's']
['t', 'h', 'i', 's', 't', 'h', 'i', 's']
['t', 'h', 'i', 's', 't', 'h', 'i', 's', 't', 'h', 'i', 's']
and so on ... i would expect it to stuck to
['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