Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Third solution in Clear category for Flatten a List by freeman_lex
from collections.abc import Iterable
def flat_list(ar: list) -> Iterable[int]:
for i in ar:
yield from [i] if isinstance(i, int) else flat_list(i)
print("Example:")
print(list(flat_list([1, [2, 2, 2], 4])))
# 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!")
Jan. 24, 2023
Comments: