Flatten list in python

Flatten list example:

Code:

def flatten_list(x, result=None):
  
    if result is None:
        result = []
       
    for a in x:
        if isinstance(a, list):
            flatten_list(a, result)
        else:
            result.append(a)
    return result
l=[1,2,[3,4,[5,6,[7,8]]]]

print flatten_list(l)


Output:
[1, 2, 3, 4, 5, 6, 7, 8]





No comments:

Post a Comment