Possible Duplicate:
Flatten (an irregular) list of lists in Python
Hi I was working out with nested lists in python and found this to be a big problem. I know we should go with recursive functions but unable to proceed..
Possible Duplicate:
Flatten (an irregular) list of lists in Python
Hi I was working out with nested lists in python and found this to be a big problem. I know we should go with recursive functions but unable to proceed..
 
    
     
    
    If you have list of list -e.g max depth is 1 then you can use the following code:
lVals = [1,[2,3]]
res = []
for i in lVals:
    if isinstance(i, list):
        res.extend(i)
    else:
        res.append(i)
print res
>>> [1,2,3]
 
    
    def flatten(li):
    if not isinstance(li, list):
        return [li]
    rv = []
    for ll in li:
        rv.extend(flatten(ll))
    return rv
print flatten([1,2,3,4])
print flatten([1,[2,3],3,4])
print flatten([1,[2,[3,4,5]],3,4])
print flatten([1,[2,[3,4,5]],3,[]])
gives
[1, 2, 3, 4]
[1, 2, 3, 3, 4]
[1, 2, 3, 4, 5, 3, 4]
[1, 2, 3, 4, 5, 3]
