flatten a list of list

Chris Rebert clp2 at rebertia.com
Sun Aug 16 05:55:48 EDT 2009


On Sun, Aug 16, 2009 at 5:47 AM, Terry<terry.yinzhe at gmail.com> wrote:
> Hi,
>
> Is there a simple way (the pythonic way) to flatten a list of list?
> rather than my current solution:
>
> new_list=[]
> for l in list_of_list:
>    new_list.extend(l)
>
> or,
>
> new_list=reduce(lambda x,y:x.extend(y), list_of_list)

#only marginally better:
from operator import add
new_list = reduce(add, list_of_list)

#from the itertools recipes:
from itertools import chain
def flatten(listOfLists):
    return list(chain.from_iterable(listOfLists))

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list