How to determine the dimensions of a mix of lists and arrays?
<p>Consider an object that is a list of arrays: </p>

<p><code>a=[array([1,2,3]),array(2,5,10,20)]</code></p>

<p>In its own funny way, this thing has two dimensions. The list itself is one dimension, and it contains objects which are 1D. Is there an easy way to distinguish between <code>a</code> above and a list like <code>b=[1,3,6,9,11]</code> which is simply 1D, and <code>c=1</code>, which is a 0D scalar? I want a function <code>dimens()</code> such that <code>dimens(a)</code> returns <code>2</code>, <code>dimens(b)</code> returns <code>1</code>, and <code>dimens(c)</code> returns <code>0</code>.</p>

<p>I am doing it by testing the shape of the first element in the list, but I feel like there may be a cleaner approach.</p>

<pre><code>def dimens(l):
    try:
        size = len(l)
    except TypeError: # not an iterable
        return 0
    else:
        if size: # non-empty iterable
            return 1 + max(map(dimens, l))
        else: # empty iterable
            return 1

print(dimens([[1,2,3],[2,5,10,[1,2]]]))
print(dimens(np.zeros([6,5,4,3,2,1])))
</code></pre>

<p><strong>Output</strong></p>

<pre><code>3
6
</code></pre>

python arrays list numpy