Compact syntax for 0-matrix?

Kirby Urner urner at alumni.princeton.edu
Sun May 28 19:57:07 EDT 2000


Looking for good ideas for compact syntax that 
returns a list of lists, all 0 members, 
given n,m for n lists of m members each.

Example:

 >>> output = zeromatrix(3,3)  # 3 lists of 3 members each
 >>> output
 [[0,0,0],[0,0,0],[0,0,0]]
 >>> output = zeromatrix(3,4)  # 3 lists of 4 members each
 >>> output
 [[0,0,0,0],[0,0,0,0],[0,0,0,0]]

So far what I've got is:

   def zeromatrix(n,m):
        output = [0]*n
        for i in range(n): output[i]=[0]*m
        return output

But I think that's sort of ugly.

I tried:

   def zeromatrix(n,m):
        return [[0]*m]*n

which looks nicer, appeared to work, but it's actually 
reusing the same object n times.  So, using the above 
def, if you go:

 >>> output = zeromatrix(3,3)
 >>> output
 [[0,0,0],[0,0,0],[0,0,0]]
 >>> output[0][0] = 5
 >>> output
 [[5, 0, 0], [5, 0, 0], [5, 0, 0]]

... which is NOT the behavior I want.  I fell into 
the "multiple pointers to same object" trap.

The first definition gets around that problem, but
I don't think it's as compact as it could be.

Kirby





More information about the Python-list mailing list