Skip to content

Instantly share code, notes, and snippets.

@vrbadev
Created December 14, 2021 18:59
Show Gist options
  • Save vrbadev/a202b641d3e424feb439f5c0d579dd9f to your computer and use it in GitHub Desktop.
Save vrbadev/a202b641d3e424feb439f5c0d579dd9f to your computer and use it in GitHub Desktop.
Simple Python recursive function to flatten any iterable nested object to unit-depth iterable of desired type
def flatten(*parents, dtype=tuple):
# internally, lists are used because they can be easily merged and expanded
result = list()
for i in range(len(parents)):
try:
# if i-th element iterable, use recursion to flatten all its elements and merge the result with current return list
result.extend(flatten(*parents[i], dtype=list))
except TypeError:
# if not iterable, add the element to return list
result.append(parents[i])
# transform to desired return type (dtype argument)
return dtype(result)
if __name__ == "__main__":
# example
import numpy as np
print(flatten([1], [2,[3]], 4, [[[5]],6,[7]], dtype=np.array)) # prints: array([1, 2, 3, 4, 5, 6, 7])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment