Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Flattening using recursion, clearly explained solution in Clear category for Flatten a List by myusercb
def flat_list(array):
# Base case: Each time an element is not another list we return it
if not isinstance(array, list):
return [array]
# The list comprehensions does a dpth = 1 flattening from [1, [1,2]] to [1,1,2]
# flat_list(sublist) iterates over each element in the array that is not a list
# because that is captured bu the `base case`
return [item for sublist in array for item in flat_list(sublist)]
flat_list([1, [2, 2, 2], 4])
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')
May 7, 2021