Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Used itertools, chain() and isinstance() solution in Clear category for Flatten a List by H0r4c3
from itertools import chain
from collections.abc import Iterable
def flat_list(array):
def flat(array):
result = list()
for item in array:
if isinstance(item, Iterable):
c = list(chain(item))
result.extend(c)
else:
result.append(item)
print(result)
return result
while any(isinstance(item, Iterable) for item in array):
array = flat(array)
return 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')
Dec. 26, 2021
Comments: