Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created April 11, 2022 17:37
Show Gist options
  • Save vlad-bezden/55c016e752eafb1badba0c80e648eda0 to your computer and use it in GitHub Desktop.
Save vlad-bezden/55c016e752eafb1badba0c80e648eda0 to your computer and use it in GitHub Desktop.
Flatten multi-level nested iterable (list, tuple, ...)
"""Flatten multy-level nested iterable."""
from typing import Any, Iterable
def deep_flatten(data: Iterable[Any]) -> Iterable[float]:
def inner(data):
if isinstance(data, (int, float)):
return [data]
elif not data:
return []
first, *tail = data
return inner(first) + inner(tail)
return inner(data)
if __name__ == "__main__":
tests = (
([], []),
([[[1, 2], [3, 4, 5]], [[[[6, 7]]]], [8], []], [1, 2, 3, 4, 5, 6, 7, 8]),
([[1, 2], [3, 4], [5]], [1, 2, 3, 4, 5]),
)
for test in tests:
input, expected = test
result = deep_flatten(input)
assert result == expected
print("PASSED!!!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment