Find the dimensions of a multidimensional Python array

Anderson Green picture Anderson Green · Jul 8, 2013 · Viewed 86.2k times · Source

In Python, is it possible to write a function that returns the dimensions of a multidimensional array (given the assumption that the array's dimensions are not jagged)?

For example, the dimensions of [[2,3], [4,2], [3,2]] would be [3, 2], while the dimensions of [[[3,2], [4,5]],[[3,4],[2,3]]] would be [2,2,2].

Does Python have any built-in functions that will return all of the dimensions of a multidimensional array, or will I need to implement this function myself?

Answer

jason picture jason · Jul 8, 2013

No, there's nothing built-in because with such "arrays"1 it can be jagged and the concept of "dimensions" or "shape" doesn't make any sense at all. So, you'll have to write your own. If you can make an assumption of uniformity along all dimensions, you can proceed as follows:

dim1 = len(a)
dim2 = len(a[0])
dim3 = len(a[0][0])
.
.
.

It'd be pretty easy to make this recursive to handle all dimensions. This should do it:

def dim(a):
    if not type(a) == list:
        return []
    return [len(a)] + dim(a[0])

But if you need something like this, you might want to consider looking at NumPy arrays which have numpy.ndarray.shape which would give you what you're looking for.

from numpy import array
l = [[2, 3], [4, 2], [3, 2]]
a = array(l)
print a.shape

Output

(3, 2)

1 In scare quotes because you're not really looking at array, you're looking at a list, or a list of lists, or a list of list of lists....