I have a list looks like this:
[[1,2,3],[1,2],[1,4,5,6,7]]
and I want to flatten it into [1,2,3,1,2,1,4,5,6,7]
is there a light weight function to do this without using numpy?
arrayslistpython
I have a list looks like this:
[[1,2,3],[1,2],[1,4,5,6,7]]
and I want to flatten it into [1,2,3,1,2,1,4,5,6,7]
is there a light weight function to do this without using numpy?
Best Answer
Without numpy (
ndarray.flatten
) one way would be usingchain.from_iterable
which is an alternate constructor foritertools.chain
:Or as another yet Pythonic approach you can use a list comprehension :
Another functional approach very suitable for short lists could also be
reduce
in Python2 andfunctools.reduce
in Python3 (don't use this for long lists):To make it slightly faster you can use
operator.add
, which is built-in, instead oflambda
:benchmark:
A benchmark on @Will's answer that used
sum
(its fast for short list but not for long list) :