Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Flatten a List by OleksandrIvanov
def flat_list(array):
# creating a new list
flat_list = []
# Since we do not know how many levels of nesting is there, we need to use a recursion
# a new function is defined
def get_it_flat(data):
# iterating through the data
for i in data:
# if the item in our array has type list
if type(i) == list:
# we are going to use the function again
get_it_flat(i)
# else: we are adding the item/number to our new "flat" list
else:
flat_list.append(i)
# passing on the result
return flat_list
# running the recursive function on the array and returning the "flat" list
return get_it_flat(array)
if __name__ == '__main__':
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')
April 28, 2020
Comments: