1

How to make a nested list to the one-dimensional without using modules? Example:

input : [[[2]], [4, [5, 6, [6], 6, 6, 6], 7]
output: [2, 4, 5, 6, 6, 6, 6, 6, 7]

I wrote function

result = []
def flat_list(array):
    for x in array:
        if isinstance(x, list):
            flat_list(x)
        else:
            result.append(x)
            print(x)
    return result

I want to do it using only function and not using any variables outside. Thanks

Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
Duxo
  • 21
  • 4

1 Answers1

1

You can do that with a recursive function as below:

inList = [[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]
def flatten(l):
    r = []
    for elem in l:
        if isinstance(elem,list):
            r += flatten(elem)
        else:
            r.append(elem)
    return r
print(flatten(inList))

Result:

[2, 4, 5, 6, 6, 6, 6, 6, 7]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
  • With re: import re list1 = [[[2]], [4, [5, 6, [6], 6, 6, 6], 7]] str1 = str(list1) print (str1) str1 = re.sub(r'\\[|\\]', '', str1) print (str1.split()) – Venfah Nazir Mar 22 '19 at 17:43