-1

I want to combine list of lists, here is the below sample

mylist = [[['a', 'b'], ['c', 'd']],
          [['e', 'f'], ['g', 'h']]]

and the output should be:

output = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

I also tried using itertools, but here is what it returned

>>> combined = list(itertools.chain.from_iterable(mylist))
>>> combined
>>> [['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']]

How I can achieve this ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Can anyone highlight whats I'm missing?

Asif
  • 479
  • 2
  • 6
  • 12

3 Answers3

3

The reason why the itertools method didn't work is because what you have isn't a list of lists, but a list of lists of lists. itertools is working properly, its just flattening the list once. Calling the exact same function again with the partially flattened list as an argument will work:

flat = list(itertools.chain.from_iterable(itertools.chain.from_iterable(mylist)))

Or, a simple list comprehension solution:

flat = [item for slist in mylist for sslist in slist for item in sslist]

This basically translates to:

for slist in mylist:
    for sslist in slist:
        for item in sslist:
            flat.append(item)

Keep in mind, both these solutions are only good for dealing with double nesting. If there is a chance you will have to deal with even more nesting, I suggest you look up how to flatten arbitrarily nested lists.

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
2

As others have noted, you have two levels here so you need two calls to chain. But you don't actually need the from_iterable call; you can use the * syntax instead:

list(itertools.chain(*itertools.chain(*mylist)))
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

With numpy.ndarray.flatten():

import numpy as np

mylist = [ [['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']] ]    
a = np.array(mylist).flatten().tolist()

print(a)

The output:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105