When is List Comprehension inappropriate?
BJörn Lindqvist
bjourne at gmail.com
Mon Mar 19 12:29:40 EDT 2007
On 19 Mar 2007 07:41:59 -0700, Ben <bensherman at gmail.com> wrote:
> 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)]
I would definitely not use list comprehension in this case. While they
may be faster, Psyco is great here. Also, if you have lots of 2d-loops
like "for x in something: for y in something:", then it could be more
beautiful to separate the iteration from the task:
def iterimage(im, width, height, step = 1):
for y in range(0, height, step):
for x in range(0, width, step):
yield (x, y), im.getpixel((x, y))
Then the list comprehension becomes a little more manageable:
even2 = [(pos, col) for pos, col in iterimage(im, width, height, 2)]
Although this must definitely be the slowest of all the different approaches.
--
mvh Björn
More information about the Python-list
mailing list