Flatten in Python - breaking

Ages ago I got this code from this forum and it’s always worked well.

It still works well with numbers but if I feed it stings it crashes.

Any idea why?


# Load the Python Standard and DesignScript Libraries
import sys
import clr
import collections
 
def flattenList(unflattened_list):
    if isinstance(unflattened_list,collections.Iterable):
        return [sub_element for element in unflattened_list for sub_element in flattenList(element)]
    else:
        return [unflattened_list]

OUT = flattenList(IN[0])

It’s a recursive function and it goes recursively every time the statement if isinstance(unflattened_list,collections.Iterable) is true. This will always be true for strings since they are iterable unlike integers. So try changing this statement for something like:

if isinstance(unflattened_list,collections.Iterable) and not isinstance(unflattened_list,str):

5 Likes

it is also possible to avoid the use of the collections method, this way you’re safe every time you flat a list:

lst_flatten = lambda lst: [i for sub in lst for i in lst_flatten(sub)] if isinstance(lst, list) else [lst]

5 Likes

Hi @Alien maybe you can try with DSCore


from

Cheers

1 Like