FAQ
"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

Search Discussions

Discussion Posts

Previous

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 7 of 7 | next ›
Discussion Overview
grouppython-list @
categoriespython
postedAug 31, '03 at 10:36a
activeAug 31, '03 at 8:05p
posts7
users6
websitepython.org

People

Translate

site design / logo © 2022 Grokbase