# GHPython Universal flatten Tree (structure)

**URL:** <https://discourse.mcneel.com/t/ghpython-universal-flatten-tree-structure/206227>\
**Category:** Scripting\
**Tags:** windows, ghpython\
**Created:** [June 21, 2025, 9:26pm UTC](https://discourse.mcneel.com/t/ghpython-universal-flatten-tree-structure/206227 "2025-06-21T21:26:43Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![gch](https://sea3.discourse-cdn.com/mcneel/user_avatar/discourse.mcneel.com/gch/32/662915_2.png) [@gch](https://discourse.mcneel.com/u/gch)\
**Post date:** [June 21, 2025, 9:26pm UTC](https://discourse.mcneel.com/t/ghpython-universal-flatten-tree-structure/206227/1 "2025-06-21T21:26:43Z")

</div>

Coding in GHPython it would be usefull to have an unniversal flatten to handle mixed data types, and sort it all out from python to grasshopper.

def flatten\_all(obj):  
from ghpythonlib.treehelpers import flatten  
from Grasshopper import DataTree  
from System.Collections import IEnumerable

```
# If the object is a DataTree, extract its branches and concatenate all items
if isinstance(obj, DataTree):
    return [item for branch in obj.Branches for item in branch]

# If the object is a .NET collection (e.g. direct output from gh.Flatten)
elif isinstance(obj, IEnumerable) and not isinstance(obj, (str, bytes)):
    try:
        # Use GH helper to flatten lists of lists
        return flatten(obj)
    except:
        pass

# If the object is a Python list or tuple (nested structure)
elif isinstance(obj, (list, tuple)):
    flat = []
    for item in obj:
        # Recurse into nested structures
        flat.extend(flatten_all(item))
    return flat

# For any other object, return it as a single-item list
else:
    return [obj]

```
