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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 for showing a generator. The input can be arbitrarily large and this will perform well.
In my software (Blender ... use python3) ... I got this error with this kind of solution : "global name "collection" is not difined"
ops ... it's a module I missed to import. But now the error is about "basestring".
@Jean-FrancoisGallant You must be using Python 3. Use str instead of basestring.
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.

1 Comment

this one look like simple ! thanks ! And just because it's working as is without testing ! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.