[SciPy-user] Internal parameter changes while appending scipy.stats function to a list

josef.pktd@gmai... josef.pktd@gmai...
Wed Apr 22 14:23:16 CDT 2009


On Wed, Apr 22, 2009 at 1:12 PM, Wei Xie <weixie2007@gmail.com> wrote:
> Dear Scipy users:
>
> While playing SCIPY (numpy version 1.3.0, scipy version 0.7.0, windows), it
> seems sometimes the internal parameters change quite unexpectedly.  For
> example,
>
>>>> from scipy.stats import norm
>>>> from numpy.random import normal
>
>>>> e = []
>>>> e.append((1,lambda q:norm.ppf(q,loc=1,scale=0.1),lambda
>>>> sz=1:normal(loc=1,scale=0.1,size=sz)))
>>>> e.append((10,lambda q:norm.ppf(q,loc=10,scale=0.1),lambda
>>>> sz=1:normal(loc=10,scale=0.1,size=sz)))
>>>> e.append((100,lambda q:norm.ppf(q,loc=100,scale=0.1),lambda
>>>> sz=1:normal(loc=100,scale=0.1,size=sz)))
>
> This one works as
>>>> e[0][1](0.5)
> 1.0
>>>> e[1][1](0.5)
> 10.0
>>>> e[2][1](0.5)
> 100.0
>
> suggests the internal location parameters still holds the value as assigned.
>
> On the other hand:
>>>> d = []
>>>> for i in (1,10,100): d.append((i,lambda
>>>> q:norm.ppf(q,loc=i,scale=0.1),lambda sz=1:normal(loc=i,scale=0.1,size=sz)))
>
> does not work, as
>
>>>> d[0][1](0.5)
> 100.0
>>>> d[1][1](0.5)
> 100.0
>>>> d[2][1](0.5)
> 100.0
>
> suggess the internal loc parameters to 100.0, i.e., the last one.
>
> I am a bit puzzled by this finding as I am expecting lambda expression will
> give me a closure and therefore the internal parameter loc and scale should
> not change.
>
> I am looking forward to your input.  Thanks.
>
> Wei
>

That's a python question not related to stats, see minimal example below.
I don't remember the exact arguments on binding of the variables, but
this is a recurrent discussion on the python mailing list. You can
search the python list.

Josef

li = []
for i in range(5):
    li.append(lambda (x): x+i)

print li[0](1)
print li[3](1)

for ff in li:
    print ff(1)



def nest(ii):
    return lambda (x): x+ii

li2 = []

for i in range(5):
    li2.append(nest(i))

print li2[0](1)
print li2[3](1)
for ff in li2:
    print ff(1)


this prints:
5
5
5
5
5
5
5
1
4
1
2
3
4
5


More information about the SciPy-user mailing list