0

the below code snippet flattens the nested list and the elements to the new list recursively but couldn't append all the elements to the list.

expected output : [1,2,4,5,6,7,5,8]

my output : [1,2,8]

def foo(l): 
   result = []
   for i in l:
     if type(i)==list:
       foo(i)
     else:
       result.append(i)
return result


input_list = [1,2,[4,5,[6,7],5],8]

print (foo(input_list))
Community
  • 1
  • 1
Ravi
  • 327
  • 1
  • 4
  • 14

1 Answers1

5

You are resetting result in each call. Pass it inside the function.

def foo(l,result): 
  for i in l:
   if isinstance(i,list):
     foo(i,result)
   else:
     result.append(i)
  return result


input_list = [1,2,[4,5,[6,7],5],8]
result=[]
print (foo(input_list,result))

Output:

[1, 2, 4, 5, 6, 7, 5, 8]
Rahul Verma
  • 2,946
  • 14
  • 27