Python flatten list

aDistances= IN[0]
aDistancesnew= []
aFlatdistancesnew = []

for i in aDistances:
	sDistance = i
	if sDistance > "0":
		x= sDistance.split(",")[-1][:-6][10:]

the above script generates a list of lists, offcourse it is simple flattened with list.flatten in dynamo. But i would like to how this can be done in python:
so i added this peace of code to my script:

for sublist in aDistancesnew:
    for item in sublist:

but than I get an error: TypeError: iteration over non-sequence of type int on the second line, so apparently i am not looping over a list but over an object instead.

what am i doing wrong?

1 Like

What’s an example of your input data? The second snippet of code you posted should work for a 2D list but the error suggests it is only a 1D list.


x= sDistance.split(",")[-1][:-6][10:]

could be condensed slightly to

x= sDistance.split(",")[-1][10:-6]

As Thomas has noted, your list is most likely not nested. If your list is supposed to be nested, you can flatten it like this:


The above code will also only work for a list with a single level of nesting. If your list has varied levels of nesting, a recursive approach would be more appropriate.

this is the input list. Actually a list with lines (distances) from geometries to another single geometry, in order to find the closest distance from any building to a pakr, or train station, or whatever.

1 Like


Wouldn’t it would be easier to use Curve.Length to get the length of the line and then round to your desired accuracy rather than converting the Line to a String using String from Object and then splitting it in Python?


that sounds much easier, will try this. (searched already for line.length, but that doesnt exists and did not thought about curve.length)

works very well!

Lines (and arcs, bsplines, ellipses etc) are all forms of Curves so the generic actions and properties of Curves will work on Lines too. That’s why there aren’t many specific Line properties—they’re under Curve

learned something. Thanks.

Hey @jochem25,

To basically rebuilt the dynamo node List.Flatten, you can import the ‘DSCoreNodes’ in python as an option to use some of the out of the box nodes within a python nodes.

# Load the Python Standard and DesignScript Libraries
import sys
import clr
from DSCore.List import Flatten
OUT = Flatten(IN[0])

Just wanted to drop this in this older post in case you were looking for a different way to flatten your lists within python.