may be a dumb question,but I can't understand why?

Terry Reedy tjreedy at home.com
Wed Nov 14 02:01:47 EST 2001


"Aaron Sterling" <dhaaron at hotpop.com> wrote in message
news:1103_1005719571 at t4q4p0...
> > the following function is in bpnn.py
> > def makeMatrix(I, J, fill=0.0):
> >     m = []
> >     for i in xrange(I):
> >         m.append([fill]*J)
> >     return m

This makes a matrix of J equal but *different* rows.

> > I rewrite it to :
> > def makeMatrix(I, J, fill=0.0):
> >     m=[[fill]*J]*I
> >     return m

This makes a matrix of J references to the *same* row

> > the result is defference
> > Can someone tell me the defference between the two function?

The first is almost certainly what you want.  The second will almost
certainly lead to unexpected bad behavior.

> it seems to work alright on my machine.

That makeMatrix2 runs is not the question.  Its the behaviour of the
result.

 I defined a function to test it to arbitrary parameters without a
proplem.
>
> def test(max):
>     i = j = 0
>     for i in xrange(max):
>         for j in xrange(max):
>             if makeMatrix(i, j) != makeMatrix2(i, j):
>                 print i, j

run

m1 = makeMatrix(5,5,0)
m2 = makeMatrix2(5,5,0)
print m1 == m2
m1[1][1] = m2[1][1] = 1
print m1 == m2

Terry J. Reedy






More information about the Python-list mailing list