Creating multi-dimensional arrays

spam_buster_2000 at yahoo.com spam_buster_2000 at yahoo.com
Wed Aug 8 04:55:21 EDT 2001


I've been writing a couple of programs recently which use multi-dimensional arrays of
a predefined size, and I was wondering if there was a standard idiomatic way of creating 
these in Python. I'm not looking to restrict the arrays to contain specific types, so just 
pointing me to Numeric isn't the answer here.

There are two ways I've been using to create these arrays:

First way (simple, pretty):

>>> a = [[[0 for x in range(10)]
...          for y in range(10)]
...          for z in range(10)]

Which I suppose has the advantage of documenting exactly what each dimension indicates.

Second way (more general):

	from copy import deepcopy

	def makearray(dimensions, init=None):
		if len(dimensions) == 1:
			array = [init]*dimensions[0]
		else:
			subarray = makearray(dimensions[1:], init)
			array = [deepcopy(subarray) for i in range(dimensions[0])]

		return array

	a = makearray((10,10,10), 0)

I'm sure this isn't particularly efficient, though (and has no error checking...).

Is there an obvious better way I should be using (the thing that comes to mind is a class
which would use a 1 dimensional array and pretend to be multidimensional, a lot like Numeric)?

-- 
Jon



More information about the Python-list mailing list