bad recursion, still works
oj
ojeeves at gmail.com
Wed Jul 16 08:14:33 EDT 2008
On Jul 16, 1:09 pm, Jeff <jeffo... at gmail.com> wrote:
> On Jul 15, 7:21 pm, Michael Torrie <torr... at gmail.com> wrote:
>
> > iu2 wrote:
> > > I still don't understand: In each recursive call to flatten, acc
> > > should be bound to a new [], shouldn't it? Why does the binding happen
> > > only on the first call to flatten?
>
> > Nope. In each new call it's (re)bound to the same original list, which
> > you've added to as your function continues--it's mutable. Default
> > variables that are bound to mutable objects are one of the big caveats
> > that is mentioned in the FAQ.
>
> Is this avoidable by using a call to list() in the definition instead?
No.
Probably what you'd want to do, is something like this:
def func(arg1, arg2=None):
if arg2 is None:
arg2 = list()
...
So you create a list at runtime if arg2 has its default value.
More information about the Python-list
mailing list