Last active
March 5, 2017 14:42
-
-
Save lovasoa/fe6a156c843f7fba1930acab2faeac96 to your computer and use it in GitHub Desktop.
flatten an array of arbitrarily nested arrays into a flat array (e.g. [[1,2,[3]],4] -> [1,2,3,4])
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Small module to flatten iterables | |
""" | |
def flatten(obj): | |
"""Flatten any nested iterables. | |
>>> flatten([[1,2,[3]],4]) | |
[1, 2, 3, 4] | |
It works with any iterable | |
>>> flatten([1,2,(3,4)]) | |
[1, 2, 3, 4] | |
It works with any depth, including 0 | |
>>> flatten([[[[[[[[[[1]]]]]]]]]]) | |
[1] | |
>>> flatten(1) | |
[1] | |
""" | |
result = [] | |
# We use python's duck-typing to detect if an object is iterable | |
try: | |
for elem in obj: | |
result += flatten(elem) | |
except TypeError: | |
result = [obj] | |
return result | |
if __name__ == '__main__': | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment