Flatten list of list in Grasshopper Python

Dear all,
I have a list of list and want to flatten it in python.
I try a for loop and get a runtime error. Please advise what to be modified.
Appreciate your support!
Loc.

First, you need to set your input to TreeAcess, and then you can convert your tree to nested lists (lists of lists) in Python using tree_to_list.

import ghpythonlib.treehelpers as th
tree = th.tree_to_list(x)
a = []
for list in tree:
    for item in list:
        a.append(item)

Flatten.gh (14.0 KB)

1 Like

I think this would work:

flattened = []
for list in x:
    for item in list:
        flattened.append( item )
a = flattened

Thank you @Mahdiyar It works great. btw, happy birthday :slight_smile:

Hi @Mahdiyar,
Just wonder why can’t we set input directly as List Access but need to choose Tree Access then convert to list again? (I tried List Access but it does not work but dont know why)


I then want to have b as sum of items in each small lists and now List access works/ not tree access:

It’s glad that you could give some explanations.
Thank you in advance!
Flatten_re.gh (15.7 KB)

If we set to ItemAccess, Python component will run as many time as the number of items in our data (6 times in this example), and each time you have only access to one item.


If we set to ListAccess, Python component will run as many times as the number of lists in our data. (3 times in this example), and each time you have only access to items in one branch.

If we need to have access to all the items in all branches, we need to set the input to TreeAccess.

In this situation each time you only need to have access to items in one branch, But whenever we set the input to TreeAccess we have full control of our data in python:

import ghpythonlib.treehelpers as th
tree = th.tree_to_list(x)
a = []
b = []
for list in tree:
    b.append(sum(list))
    for item in list:
        a.append(item)

Flatten.gh (14.5 KB)

2 Likes

Hi @Mahdiyar,
When I try to convert x (tree access) with 19 branches by tree_to_list, I expect to receive a List N=19. However the result is only show from branch {0;0} to {0;8}. The rest one {1;i} does not show up.
Not sure if I did misunderstand the function?
Really appreciate your explanation24rum.gh (46.8 KB) .

That treehelper function will generate a nested Python list that represents the actual structure of the datatree. If you’re simply trying to iterate the tree branches and make a 2D nested list, you can do something like this:

list_x = [list(b) for b in x.Branches]

2 Likes