Search code examples
pythonpython-itertools

How to flatten a list of lists of lists in python


I've seen a couple answers on how to flatten lists of the form

[1,[1,2],[3]]    
print list(itertools.chain(*[1,[1,2],[3]]))  

but how do you flatten lists like this:

[[1],[[1,2],[3]]]

print list(itertools.chain(*[[1],[[1,2],[3]]]))
[1, [1, 2], [3]]

Solution

  • I usually use this recipe:

    import collections
    
    
    def flatten(l):
    
        for el in l:
            if isinstance(el, collections.Iterable) and not isinstance(el, str):
                for sub in flatten(el):
                    yield sub
            else:
                yield el
    
    
    print(list(flatten([[1],[[1,2],[3]]])))
    # [1, 1, 2, 3]