Skip to content

Instantly share code, notes, and snippets.

@Alir3z4
Last active December 16, 2020 12:57
Show Gist options
  • Save Alir3z4/8659fd1daf6d33dfbfe8902e3c024c49 to your computer and use it in GitHub Desktop.
Save Alir3z4/8659fd1daf6d33dfbfe8902e3c024c49 to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers.
from typing import List
def flatten_list(items: List) -> List[int]:
"""
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers.
e.g. [[1,2,[3]],4] -> [1,2,3,4].
>>> nested: list = [[1, 2, [3, [4, 4, 8, [8, 8, 7]]]], 4, [], None]
>>> expected: List[int] = [1, 2, 3, 4, 4, 8, 8, 8, 7, 4]
>>> assert flatten_list(nested) == expected
"""
flatten: List[int] = []
for item in items:
if isinstance(item, list):
flatten.extend(flatten_list(item))
elif isinstance(item, int):
flatten.append(item)
return flatten
from typing import List
from flatten import flatten_list
def test_flatten() -> None:
nested: list = [[1, 2, [3, [4, 4, 8, [8, 8, 7]]]], 4, [], None]
expected: List[int] = [1, 2, 3, 4, 4, 8, 8, 8, 7, 4]
assert flatten_list(nested) == expected
if __name__ == "__main__":
test_flatten()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment