Search code examples
pythonlist-comprehensionnested-lists

Flatten doubly nested lists


How to convert this:

[[[1,2,3], ['a','b','c']], [[4,5], ['d','e']], [[6,7,8,9], ['f','g','h','i']]]

to this:

[[1,2,3,4,5,6,7,8,9], ['a','b','c','d','e','f','g','h','i']]

Knowing python, there must be some way using zip and list comprehensions.


Solution

  • Looks like a task for zip and itertools.chain.from_iterable().

    data = [[[1,2,3], ['a','b','c']], [[4,5], ['d','e']], [[6,7,8,9], ['f','g','h','i']]]
    list(zip(*data))
    

    This will give you

    [([1, 2, 3], [4, 5], [6, 7, 8, 9]), (['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i'])]
    

    Now apply chain.from_iterable for the inner lists:

    data = [[[1,2,3], ['a','b','c']], [[4,5], ['d','e']], [[6,7,8,9], ['f','g','h','i']]]
    print([list(itertools.chain.from_iterable(inner)) for inner in zip(*data)])