question regarding list comprehensions

Pat Pat at junk.com
Mon Oct 20 10:20:03 EDT 2008


I have written chunks of Python code that look this:

     new_array = []
     for a in array:
         if not len( a ):
             continue
         new_array.append( a )

and...

     string = ""
     for r in results:
         if not r.startswith( '#' ):
             string =+ r

It seems that a list comprehension could clean up the code, but I seem 
to have a mental block on list comprehensions.  I've read up a lot on 
this subject in my books and on the Internet and for whatever reason, 
I'm having problems with this idiom (if that's the correct expression).

I've made a number of attempts to solve this on my own but I keep 
getting errors.

Could someone please tell me how I could convert the above code to 
something more elegant but readily understandable?

Finally, if someone could point me to a good tutorial or explain list 
compressions I would be forever in your debt.



More information about the Python-list mailing list