arrayspython-3.xlistmultidimensional-array

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.


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]
    

    Version 2.0 : Same output as above

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