Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a hetrogenous list of list into a single list in python?

I have a list of objects where objects can be lists or scalars. I want an flattened list with only scalars. Eg:

L = [35,53,[525,6743],64,63,[743,754,757]]
outputList = [35,53,525,6743,64,63,743,754,757]

P.S. The answers in this question does not work for heterogeneous lists. Flattening a shallow list in Python

like image 764
balki Avatar asked Nov 29 '22 09:11

balki


1 Answers

Here is a relatively simple recursive version which will flatten any depth of list

l = [35,53,[525,6743],64,63,[743,754,757]]

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

print flatten(l)
like image 164
Nick Craig-Wood Avatar answered Dec 05 '22 14:12

Nick Craig-Wood