Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
using recursion solution in Clear category for Flatten a List by Marco_Monti
def flat_list(array):
list=[]
for element in array:
if isinstance(element,int): #if the element is an integer:
list.append(element)
else:
list=list+flat_list(element) #if the element is a list, use the same function again to find the element in it (recursion)
return list
if __name__ == '__main__':
print(flat_list([1, 2, 3]))
print(flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]))
assert flat_list([1, 2, 3]) == [1, 2, 3], "First"
assert flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4], "Second"
assert flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7], "Third"
assert flat_list([-1, [1, [-2], 1], -1]) == [-1, 1, -2, 1, -1], "Four"
print('Done! Check it')
May 13, 2020
Comments: