Skip to content

Instantly share code, notes, and snippets.

@kracekumar
Created March 12, 2014 19:07
Show Gist options
  • Save kracekumar/9514038 to your computer and use it in GitHub Desktop.
Save kracekumar/9514038 to your computer and use it in GitHub Desktop.
Flatten nested data structure in python 3
from collections import Iterable
def flatten(items):
for item in items:
if isinstance(item, Iterable):
yield from flatten(item)
else:
yield item
nested = [1, 3, [3, [4, 5, [6]]]]
print(list(flatten(nested)))
[1, 3, 3, 4, 5, 6]
@kracekumar
Copy link
Author

Python 2 version

In [49]: x
Out[49]: [[1, 2, [3]], 4]

In [50]: def flatten(items):
    for item in items:
        if isinstance(item, Iterable):
            for subitem in flatten(item): yield subitem
        else:
            yield item
   ....:

In [51]: list(flatten(x))
Out[51]: [1, 2, 3, 4]

   ....:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment