A performance issue when using default value
keakon
keakon at gmail.com
Mon Feb 1 00:32:06 EST 2010
On 2月1日, 下午1时20分, alex23 <wuwe... at gmail.com> wrote:
> 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.
Thank you, I got it.
The default value is mutable, and can be reused by all each call.
So each call it will append 1 to the default value, that's very
different than C++.
More information about the Python-list
mailing list