Python: Flatten an irregular list of list of list


#1

HI,

Is there any quick/easy way to flatten a list in python? I’ve searched but so far all the solutions are messy or use an external module.

Any ideas?

-M


#2

Hi Miguel,

Check these two topics:



#3

Hi @djordje,

I’m looking for a small function that i could implement. I’m not working inside grasshopper, so this solutions are not really helpful.

Thanks,

-M


#4

I found a solution:

def flatten(lst):
    return sum( ([x] if not isinstance(x, list) else flatten(x) for x in lst), [] )

I found this web http://rosettacode.org/wiki/Flatten_a_list#Python and it is pretty neat and helpful.

-M


#5

Would itertools do what you want?

–Mitch


#6

Terribly sorry for that. Grasshopper seems to be on my mind.

Googling came up with this:
http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html