When is List Comprehension inappropriate?

Ben bensherman at gmail.com
Mon Mar 19 15:41:59 CET 2007


I have recently learned how list comprehension works and am finding it
extremely cool.  I am worried, however, that I may be stuffing it into
places that it does not belong.

What's the most "pythony" way to do this:

even = []
for x in range(0,width,2):
    for y in range(0,height,2):
        color = im.getpixel((x,y))
        even.append(((x,y), color))

versus list comprehension:

even2 = [((x,y), im.getpixel((x,y))) for x in range(0,width,2) for y
in range(0,height,2)]

Is there a computational difference in creating a blank list and
appending to it versus doing a list comprehension?   Are there
advantages to it outside of short and pretty code?

Feel free to tell me a different way to do this, as well.

Thanks,
Ben




More information about the Python-list mailing list