Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
list flattening solution in Clear category for Flatten a List by maldavian
from collections.abc import Iterable
def flat_list(array: list[int]) -> Iterable[int]:
e = []
for item in array:
if isinstance(item, list):
e.extend(flat_list(item))
else:
e.append(item)
return e
print("Example:")
print(list(flat_list([1, 2, 3])))
# These "asserts" are used for self-checking
assert list(flat_list([1, 2, 3])) == [1, 2, 3]
assert list(flat_list([1, [2, 2, 2], 4])) == [1, 2, 2, 2, 4]
assert list(flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]])) == [
2,
4,
5,
6,
6,
6,
6,
6,
7,
]
assert list(flat_list([-1, [1, [-2], 1], -1])) == [-1, 1, -2, 1, -1]
print("The mission is done! Click 'Check Solution' to earn rewards!")
March 18, 2024