Flattening a list recursively [duplicate]
Possible Duplicate:
Flatten (an irregular) list of lists in Python
I am having trouble using python to recursively flatten a list. I have seen a number of methods that require list comprehension and various methods requiring imports however I am looking for a very basic method to recursively flatten a list of varying depth that does not use any for loops either. I had a series of test however there are two I cannot pass
flatten([[[[]]], [], [[]], [[], []]]) # empty multidimensional list
flatten([[1], [2, 3], [4, [5, [6, [7, [8]]]]]]) # multiple nested list
My code
def flatten(test_list):
#define base case to exit recursive method
if len(test_list) == 0:
return []
elif isinstance(test_list,list) and type(test_list[0]) in [int,str]:
return [test_list[0]] + flatten(test_list[1:])
elif isinstance(test_list,list) and isinstance(test_list[0],list):
return test_list[0] + flatten(test_list[1:])
else:
return flatten(test_list[1:])
I would appreciate some advice.
This handles both of your cases, and I think will solve the general case, without any for loops:
def flatten(S):
if S == []:
return S
if isinstance(S[0], list):
return flatten(S[0]) + flatten(S[1:])
return S[:1] + flatten(S[1:])
li=[[1,[[2]],[[[3]]]],[['4'],{5:5}]]
flatten=lambda l: sum(map(flatten,l),[]) if isinstance(l,list) else [l]
print flatten(li)