Recursive list comprehension

Nick Coghlan ncoghlan at iinet.net.au
Mon Dec 6 06:11:05 EST 2004


Peter Nuttall wrote:
> I think you do it with a generator like this:
> 
> def flatten(nested):
>   for sublist in nested:
>     for element in sublist:
>       yield element
> 
> n=[['N', 'F'], ['E'], ['D']]
> output=[]
> 
> for value in flatten(n):
>   output.append(value)
> 
> print output

I highly recommend learning about the stdlib module "itertools" (I only really 
looked into it recently). The above can be done in 3 lines (counting imports):

   from itertools import chain
   n = [['N', 'F'], ['E'], ['D']]
   print [chain(*n)]

Documentation:
   http://www.python.org/doc/2.3.4/lib/itertools-functions.html

Cheers,
Nick.



More information about the Python-list mailing list