Recursive list comprehension

Peter Nuttall p.s.nuttall at dur.ac.uk
Mon Dec 6 05:21:24 EST 2004


On Monday 06 Dec 2004 09:26, Timothy Babytch wrote:
> Hi all.
>
> I have a list that looks like [['N', 'F'], ['E'], ['D']]
> I try to make it flat one: ['N', 'F', 'E', 'D']
>
> How can I archieve such an effect with list comprehension?
> Two cycles did the job, but that way did not look pythonic..
>
> I tried
> print [x for x in y for y in c_vars]
> and got NameError: name 'y' is not defined.
>
> --
> Timothy Babytch

Hi,

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

Have a merry Christmas

Peter Nuttall

 



More information about the Python-list mailing list