Newbie: How do I implement an 2 element integer array in Python.?

Alex Martelli aleaxit at yahoo.com
Thu Oct 12 05:10:53 EDT 2000


"Rainer Deyke" <root at rainerdeyke.com> wrote in message
news:u97F5.64035$g6.28185416 at news2.rdc2.tx.home.com...
    [snip]
> > >MyArray = [[0 for i in range(16)] for j in range(100)]
> > >MyArray[5][4] = 7
> >
> > Why zero rather than None?
>
> I think BASIC initializes to 0 (although I could be wrong here).
Therefore

In Visual Basic 6,
    Private Sub Form_Load()
        Dim x(10, 7)
        MsgBox TypeName(x(2, 4))
    End Sub
displays "Empty" when run.  In the docs (MSDN) it explains:

"""
Empty
Indicates that no beginning value has been assigned to a Variant variable.
An Empty variable is represented as 0 in a numeric context or a zero-length
string ("") in a string context.
"""

Your impression that 0 is stored for uninitialized cells of an array may
thus
come from the 'implicit coercion' of Empty to 0 -- just like somebody else
might
have received the equally misleading impression that said uninitialized
cells
are set to the empty-string, because of the _other_ implicit coercion.  It
all
depends on what context you're using it in (the "TypeName" call does no
implicit coercion -- it returns information on the ACTUAL type...).

If your array's declaration was
        Dim x(10, 7) as Integer
or
        Dim x(10, 7) as String
then the point would also be moot.  But Python has no type-declarations, so
there is no direct equivalent.


> 0 is most consistent with the original poster's experience.  There are
cases
> where None is the better choice, but there are also cases where 0 is
> superior (example: the array is used to store accumulators).

Yes, it does depend on "context of intended usage".  None is best if the
intention is that no array-cell be used without being explicitly set first;
'', or 0, or 0L, or 0.0, may each be best for different intended-uses.

In other words, encapsulating this into a function, we might have:

def dim2(dimx, dimy, defaultValue=None):
    return [[defaultValue for i in range(dimy)] for j in range(dimx)]

and a numeric array might be built with:
    myArrayInt = dim2(16, 100, 0)
or
    myArrayLong = dim2(16, 100, 0L)
or
    myArrayFloat = dim2(16, 100, 0.0)

while non-numeric arrays remain just as easily buildable (just give
a different default...).  I think the "default of the default" might
well remain at None, but opinions may certainly differ on this!-)


Alex






More information about the Python-list mailing list