how to test for nesting inlist

Alex Martelli aleaxit at yahoo.com
Sat Jan 20 07:15:26 EST 2001


<cpsoct at my-deja.com> wrote in message news:94bhte$4iv$1 at nnrp1.deja.com...
> Is there a way to test if a list in nested and if so how deep? so that
> you could type
>
> y=[1,2,3]
> x=[1,[2,3]]
>
> howDeep(y)
> howDeep(x)
>
> and it would return 0 (no nesting) for y and 1, for x (1 level of
> nesting)
>
> Is this possible? It would seem really useful, but i don't see anything
> in the docs about how to do this.

It's not a built-in (because its usefulness is not perceived as all
that big...), but it's easy to code it yourself.  Assuming you only
care about lists and not tuples or other forms of 'nesting', e.g.:

def howDeep(x):
    if type(x)!=type([]):
        return 0
    return 1+reduce(max,map(howDeep,x),0)

Note that this returns 0 for a non-list, 1 for a list not containing
any other lists, etc; this seems more natural to me than what
you requested!  Just change both occurrence of 0 into -1 to
get exactly your specs.

Of course, either or both of the recursion and the 'functional'
approach can be removed if one so wishes, but I think this is
the simplest approach to such a typical functional-programming
question:-).


Alex






More information about the Python-list mailing list