flat a nested list in python | flat implementation in python

Some time we have a nested list which we want to make in one dimensional array or you can say we want to flat it.

def flat(arr):
    #base condition
    if type(arr) != list: #[[2,3]]
        return [arr]
    elif len(arr) == 1:
        return flat(arr[0])
    else:
        return flat(arr[0]) + flat(arr[1:])

Example:

flatArray = flat([1,[2,3],[4,[5,6, [7]]]]]
print(flatArray) #[1,2,3,4,5,6,7]

Leave a Reply