2D Arrays

Alex Martelli aleaxit at yahoo.com
Sat Sep 9 19:11:50 EDT 2000


"Jad Courbage" <jad at altern.org> wrote in message
news:dKuu5.794$8s.2590844 at nnrp3.proxad.net...
> Hi,
>
> Could anybody tell me the command to build a 2D array ? (without using the
> NumPy module)
>
> I tried something like :
>
> for i in range(0,5):
>      for j in range(0,10):
>           arr[i][j]=i*j
>
> but it doesn't work !
> Do i have to declare the array ?

There is no "declaration" involved.  However, Python lists just
don't work this way -- and it's not an issue of 1-d vs 2-d: you
don't just mention a never-before-bound variable, with a [...]
tagged on to it, and have the variable be magically bound to a
freshly created list (arrays, in Python, are quite a different
thing; see the array module, which is part of the standard
Python distribution -- you must "import array", there's no 2D
ever, etc, etc).

The only normal way to bind a variable is an "assignment" to
that variable.  So, to build a list that's probably what you
would call a '1D array', you basically have 2 choices:

-- initially bind a variable to an empty list, then append to it:
-- bind the variable right off to a list of the proper length,
    then assign to each element

I.e., either use the style:
    ar=[]
    for i in range(5):
        ar.append(i)
or:
    ar=[None]*5
    for i in range(5):
        ar[i]=i

Of course, for this particular case you can also simply
    ar=range(5)
or, in Python 2:
    ar=[i for i in range(5)]
i.e. bind the variable to a pre-constructed list in some way
or other (the second form is called 'list comprehension').


So, when you go '2-D', you have the same choices; and you
can use a different one on each axis, if you wish, so the
possibilities are many.  From the simplest/verbosest...:

arr=[]
for i in range(5):
    arr.append([])
     for j in range(10):
          arr[i].append(i*j)

to the most concise, a nested list comprehension (only
in Python 2...!):

arr=[ [i*j for j in range(10)] for i in range(5)]


Alex






More information about the Python-list mailing list