array constructor

Michael Tiomkin michael at camelot-it.com
Mon Feb 28 07:33:04 EST 2000


Tom Holroyd wrote:

> Monday hits -- more --
>
> I want a 4x4 array of zeros.  I can do
>
> from Numeric import *
> m = zeros((4,4), Float)
>
> but I'd like to do it with ordinary lists.
>
> m = [[0]*4]*4 doesn't work:
>
> >>> m = [[0]*4]*4
> >>> m[2][2] = 5
> >>> m
> [[0, 0, 5, 0], [0, 0, 5, 0], [0, 0, 5, 0], [0, 0, 5, 0]]
>
> because * doesn't make copies.  Do I have to do
>
> >>> m = [[0]*4]
> >>> for x in range(3):
> ...     m.append([0]*4)
> ...
> >>> m[2][2] = 5
> >>> m
> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 5, 0], [0, 0, 0, 0]]

 Well, the following worked for me (forcing list copy):
>>> a=[[0]*4]*4
>>> a
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> b=map(lambda x: x+[],a)
>>> b
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> b[2][3]=5
>>> b
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 5], [0, 0, 0, 0]]
>>>

> While I'm here, string.atof() and float() both barf on "123.45," while the
> C atof() doesn't.  A quick check of the code (stropmodule.c) shows that
> there is an explicit check for junk at the end of the string.  Is there
> some reason for this besides just being annoying?  :-)  I vote to remove
> it.

  In some countries, 123,456 means 1.23456e5, so you'd better avoid returning 123 on
atof('123,456'), otherwise you just let people insert more bugs in their code.  If you use a
delimiter on a list of numbers, you can use splitfields from string module.  BTW, Python could have
a better split function, like that in awk, or at least with a string of possible delimiters, and the
meaning of choosing the maximal string of a type [a1...an]*.

  Michael




More information about the Python-list mailing list