+ 1
How to flaten a list of lists in python using a recursive function ?
Hey guys, so i was reading a book about python and in some part of it, there was this fact that you can use a recursive function to flaten a list like A=[1,2,[3,4],[5,[6,7],8],[9],10] into A=[1,2,3,4,5,6,7,8,9,10]. Now i know there are many other ways to flaten a list like using pre-made modules and stuff but my question is about doing it with a recursive function. Thank you all :)
2 ответов
+ 7
One way to do this
def flat(lis,newlist):
for i in lis:
if isinstance(i,list):
flat(i,newlist)
else:
newlist.append(i)
return newlist
print(flat([1,2,3,[4,5],[6,7]],[]))
isinstance function checks if any item in original list is an instance of class List,if yes it calls the function with an argument being that item otherwise it appends the item to a newlist and returns it at the end of for loop
0
Thanks guys, they were all useful ^^ cheers