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?
totally hacky but I think it would work (depending on your data_type)
I'm not sure if this is necessarily quicker or more effective, but this is what I do:
The
flatten
function here turns the list into a string, takes out all of the square brackets, attaches square brackets back onto the ends, and turns it back into a list.Although, if you knew you would have square brackets in your list in strings, like
[[1, 2], "[3, 4] and [5]"]
, you would have to do something else.Without using any library:
Using generator functions can make your example a little easier to read and probably boost the performance.
Python 2
I used the Iterable ABC added in 2.6.
Python 3
In Python 3, the
basestring
is no more, but you can use a tuple ofstr
andbytes
to get the same effect there.The
yield from
operator returns an item from a generator one at a time. This syntax for delegating to a subgenerator was added in 3.3I'm new to python and come from a lisp background. This is what I came up with (check out the var names for lulz):
Seems to work. Test:
returns: