Possible Duplicate:
Flatten (an irregular) list of lists in Python
How would I go about flattening a list in Python that contains both iterables and noniterables, such as [1, [2, 3, 4], 5, [6]]? The result should be [1,2,3,4,5,6], and lists of lists of lists (etc.) are certain never to occur.
I have tried using itertools.chain, etc., but they seem only to work on lists of lists. Help!
So you want to flatten only 1 or 2 levels, not recursively to further depts; and only within lists, not other iterables such as strings, tuples, arrays… did I get your specs right? OK, if so, then…:
If you want a list result,
list(flat2gen(mylist))will produce it.Hope this is trivially easy for you to adapt if your actual specs are minutely different!