[Tutor] How to test a list for nesting

Michael P. Reilly arcege@shore.net
Sun, 21 Jan 2001 08:39:05 -0500 (EST)


> 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.
>  

That's because there is nothing to do this within Python itself.

The "problem" is what type would this work on, only lists?  To be
Pythonic, it should handle any sequence - but why makes an object a
sequence?  __len__, __getitem__ and __getslice__ methods.  Hmm... well,
dictionaries have __len__ and __getitem__ method, but only sequences
have __getslice__ methods.+  So we can test for slicing.

>>> def howDeep(seq):
...     # this will raise an exception if it is not a sequence
...     seq[:]
...     depths = [0]
...     for obj in seq:
...         try:
...             depths.append( howDeep(obj) + 1 )
...         except:
...             pass
...     return max(tuple(depths))
...
>>> howDeep([1,2,3])
0
>>> howDeep([1, [2], [3, [4]]])
2
>>>

Myself, I would have that this returns 1 for a sequence with no
subsequences, but these were your specifications, not mine. :)

  -Arcege

+ Unfortunately, another "inovation" of Python 2.0 has made this
distinction blury.

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------