When is List Comprehension inappropriate?

Duncan Booth duncan.booth at invalid.invalid
Mon Mar 19 20:24:48 CET 2007


"Ben" <bensherman at gmail.com> wrote:

> 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)]
> 
...
> 
> Feel free to tell me a different way to do this, as well.
> 

Untested code, but I would try to avoid calling getpixel:

data = list(im.getdata())
width, height = im.size
even = [ data[i:i+width:2] for i in range(0, width*height, 2*width)]

That creates a 2 dimensional list rather than one long list, and doesn't 
create the x,y tuples, but since they are implied by the position in the 
list I don't actually see why you would want to create them at all. You can 
calculate them separately if you actually need them.



More information about the Python-list mailing list