0

I want to know in python how to take a multidimensional array and put it in a 1D list. This thing work:

a = [[1,2],[3,4]]
sum(a,[])

I get this : [1,2,3,4]

But if I have a multidimensional with unknow dimension or not constant dimension like that :

a = [1,[3,4,[5,6,7]]]

How to get this : [1,2,3,4,5,6,7]

thanks

Jean-Francois Gallant
  • 13,583
  • 6
  • 20
  • 24

2 Answers2

3
def flatten(lis):
    for i in lis:
        if isinstance(i, collections.Iterable) and not isinstance(i, basestring):
            for sub in flatten(i):
                yield sub
        else:
            yield i

Taken from Christian's solution on this question

If you want to return a list, you can use this:

def flatten(lis):
    flat_list = []
    for i in lis:
        if isinstance(i, collections.Iterable) and not isinstance(i, basestring):
            flat_list.extend(flatten(i))
        else:
            flat_list.append(i)
    return flat_list

However, for big lists, the generator function is much more efficient as it doesn't calculate the next value until it has too, unlike lists which stores its values in memory.

Community
  • 1
  • 1
Volatility
  • 31,232
  • 10
  • 80
  • 89
1

One way is to use recursion, something like this should work:

def flatten_list(l):
    new_l = []
    for item in l:
        if type(item) == type([]):
            new_l += flatten_list(item)
        else:
            new_l.append(item)
    return new_l

I did not test this code but the idea is there.

Daniel Kuntz
  • 405
  • 4
  • 11