A performance issue when using default value

alex23 wuwei23 at gmail.com
Mon Feb 1 00:20:53 EST 2010


alex23 <wuwe... at gmail.com> wrote:
> keakon <kea... at gmail.com> wrote:
> > def h2(x=[]):
> >   y = x
> >   y.append(1)
> >   return y + []
>
> Are you aware that 'y = x' _doesn't_ make a copy of [], that it
> actually points to the same list as x?

Sorry, I meant to suggest trying the following instead:

def h2(x=None):
  if x is None: x = []
  x.append(1)
  return x + []

It's a common idiom to use None as a sentinel for this situation, esp.
where you _don't_ want a default mutable object to be reused.



More information about the Python-list mailing list