Flatten nested list while keeping the strucutre

Hi all,

Trying to flatten a nested list while keeping the structure of the list in python, how do I do it properly?

In essence, what I am trying to achieve in python script is what I am getting in List.Flatten.
see graph below for details:

Try using amt of 1 on the List.Flatten node to remove the top layer:

1 Like

Hi @Thomas_Corrie thank you for your answer, just edited the question to clarify what I am seeking. Basically, I got the answer in list.flatten node, however, I can’t mangae to get the same result from python node. So the answer I am after should be in python.

But again thanks for taking the time to solve it :slight_smile:

I see, I thought you wanted the other way around :slightly_smiling_face:

@Thomas_Corrie thanks

My Python skills are limited but how about this? There’s almost certainly a more Pythonic way to do it

# Enable Python support and load DesignScript library
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

# The inputs to this node will be stored as a list in the IN variables.
list1 = IN[0]

outlist = []
for x in list1:
	outlist.append([])
	for y in x:
		if type(y) is list:
			for z in y:
				outlist[-1].append(z)
		else:
			outlist[-1].append(y)

# Place your code below this line

# Assign your output to the OUT variable.
# OUT = flattenlist(list2)
OUT = outlist

Thank you
@Thomas_Corrie fantastic answer!

Your skills are quite advanced in python :sweat_smile:

1 Like

@saeedy3 you’re welcome, and thank you! That solution works for your particular level of nesting but if you had some deeper lists then it would be better to have a recursive function to allow for more flexibility. But if your data is in that consistent structure then this should work well.

1 Like