Flatten a list
The following methods flatten a potentially deep list using recursion.
Python: 3.0    Fatos Morina    03 Jul 2021   0
Login to upvote
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def spread(arg):
    ret = []
    for i in arg:
        if isinstance(i, list):
            ret.extend(i)
        else:
            ret.append(i)
    return ret

def deep_flatten(xs):
    flat_list = []
    [flat_list.extend(deep_flatten(x)) for x in xs] if isinstance(xs, list) else flat_list.append(xs)
    return flat_list


deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]
Copy | Download as: .py file   PNG
Share on: FB   Twitter   LinkedIn   WA
©2021 - code108labs   Contributors   Hosted on DigitalOcean   Partner website: pythoncircle.com