Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flatten a N-Dimensional Array into a 1D Array in Python

Goal: Transform a array that has N number of nested lists, into a 1D array using Python3.

Example Array: ND_array = [1, [2, 3], [4, [5, 6]], 7, [8, 9, [10, 11, 12, [13, [14, 15, 16], 17], 18], 19, 20], 21]
Transform the example array into the following result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]

A optimal solution that is not restricted on the number of dimensional the original array possess.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A simple and easy solution that works on any N-Dimensional array in python would be to utilize recursion.

oneD_array = []

def transform_array(arr):
    for x in arr:
        if type(x) == list:
            transform_array(x)
        else:
            oneD_array.append(x)
    return oneD_array

ND_array = [1, [2, 3], [4, [5, 6]], 7, [8, 9, [10, 11, 12, [13, [14, 15, 16], 17], 18], 19, 20], 21]

print(transform_array(ND_array))

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading