0

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]]
Taylor
  • 1,797
  • 4
  • 26
  • 51

1 Answers1

3

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]
Community
  • 1
  • 1
Marcin
  • 215,873
  • 14
  • 235
  • 294