Python flatten list

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

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

image
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:
        aFlatDistancesnew.append(item)

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?

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.

Incidentally:

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:

image

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.

thanks!

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?

1 Like

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.