newbie question-multidimensional arrays

Miki Tebeka miki.tebeka at zoran.com
Tue Jun 15 02:20:09 EDT 2004


Hello Doug,

> How do you define and access multidimensional arrays in Python?   I am new
> to python and come from a C and FORTRAN background and I am not sure how to
> define an array without giving the contents of the array.  Any help will be
> appreciated.   I would like to be able to read and manipulate
> multidimensional arrays using a nested loop.  I cannot find anything in the
> documentation to help me.
Python lists are arrays that can hold anything including other lists.
This makes them a multidimensional arrays as well.

For example:
def gen_2darray(m, n, initial=0):
    '''Generate two dimensional array

    We can't use [[] * n] * m since the internal arrays will point to
    the same array.
    '''
    arr = [None] * m
    for i in range(m):
        arr[i] = [initial] * n
    return arr

a = gen_2darray(10, 10)
a[4][5]

If you need fast computation with arrays have a look at numpy project.

HTH.
--
-------------------------------------------------------------------------
Miki Tebeka <miki.tebeka at zoran.com>
The only difference between children and adults is the price of the toys.




More information about the Python-list mailing list