Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Last active March 5, 2017 14:42
Show Gist options
  • Save lovasoa/fe6a156c843f7fba1930acab2faeac96 to your computer and use it in GitHub Desktop.
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])
#!/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