# [Tutor] check for nested sequences & flatten

kevin parks kp87@lycos.com
Thu, 14 Feb 2002 16:37:44 +0900

```I am trying to test for nested lists and then flatten them if need be. flatten(seq) works fine (though I wonder if this is the most efficient way to go about it --I always wondered why flatten wasn't a sequence built-in method). But here my isNested func seems broken.

>>> isNested([1, [2], [3, [4]]])
0

# 0 is clearly wrong.

# kosher

def flatten(seq):
"""flatten: completely eliminate nesting of any sequence type"""
res = []
for item in seq:
if type(item) in (TupleType, ListType):
res.extend(flatten(item))
else:
res.append(item)
return res

# what's up with this ?
#
def isNested(seq):
"""isNested: checks a list for nesting and if nested, exactly how deeply

>>> isNested([1,2,3])	         yeilds: 1
>>> isNested([1, [2], [3, [4]]])  yeilds: 3"""

seq[:]
depths = [0]
for obj in seq:
try:
depths.append(isNested(obj))
except:
pass
return max(tuple(depths))

# as i sure to be over my quota of questions for the day, i'll go away now.

Love is in the Air!

Check out Cupid School where you will learn from Matchmaker's
best and brightest.

At Cupid School you'll learn how to pair up hopeful romantics
with one another, based on their personal preferences.
If you do well- you'll be rewarded with your own
set of love bow and arrows!

Good Luck!

http://ecard.matchmaker.com/cupid0202/cupid0202.html

```