Yes, I know this subject has been covered before (here, here, here, here), but as far as I know, all solutions, except for one, fail on a list like this:
L = [[[1, 2, 3], [4, 5]], 6]
Where the desired output is
[1, 2, 3, 4, 5, 6]
Or perhaps even better, an iterator. The only solution I saw that works for an arbitrary nesting is found in this question:
def flatten(x):
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
flatten(L)
Is this the best model? Did I overlook something? Any problems?
Shamelessly taken from my own answer to another question.
This function
isinstance
, because it's evil and breaks duck typing.reduce
recursively. There has to be an answer usingreduce
.Code below:
Although an elegant and very pythonic answer has been selected I would present my solution just for the review:
Please tell how good or bad this code is?
Using
itertools.chain
:Or without chaining:
From my previous answer, this function flattens most cases I can think of. I believe this works down to python 2.3.
Circular lists
Depth first lists
Nested repeated lists:
Lists with dicts (or other objects to not flatten)
Any iterables
Here's a simple function that flattens lists of arbitrary depth. No recursion, to avoid stack overflow.
If you like recursion, this might be a solution of interest to you:
I actually adapted this from some practice Scheme code that I had written a while back.
Enjoy!